最小的,完整的例子,有答案
是的,在复制构造dtor
函数之前调用了,但不是出于您似乎认为的原因。
关键的观察是MyObject::dtor
被调用了两次(在两个不同的对象上,以防我们仍然倾向于跳到疯狂的编译器错误结论)。因此,我们猜测副本正在幕后发生,而且确实如此,尽管您可能听说过编译器确实会生成一个副本构造函数,即使您提供了不同的构造函数也是如此。
因此,如果您取消注释下面的复制构造函数,您将获得一些更好地描述正在发生的事情的输出,并且还可以正确处理mActive
标志
struct TemporaryObject
{
TemporaryObject()
:
mActive(true)
{
std::cout << "TemporaryObject::ctor mActive = " << mActive << ", this = " << (void*)this << std::endl;
}
/* TemporaryObject(const TemporaryObject& obj)
:
mActive(obj.mActive)
{
obj.mActive = false;
std::cout << "TemporaryObject::copy_ctor mActive = " << mActive << ", this = " << (void*)this << std::endl;
}*/
~TemporaryObject()
{
std::cout << "TemporaryObject::dtor mActive = " << mActive << ", this = " << (void*)this << std::endl;
// assert(!mActive);
}
mutable bool mActive;
};
struct MyObject
{
MyObject(const TemporaryObject& obj)
{
std::cout << "MyObject::ctor obj.mActive = " << obj.mActive << ", &obj = " << (void*)(&obj) << std::endl;
obj.mActive = false;
}
};
TemporaryObject SimpleFunction()
{
TemporaryObject obj;
// Do stuff
return obj;
}
int main()
{
MyObject obj = SimpleFunction();
}
输出:
TemporaryObject::ctor mActive = 1, this = 00EFF4AB
TemporaryObject::dtor mActive = 1, this = 00EFF4AB
MyObject::ctor obj.mActive = 1, &obj = 00EFF4D7
TemporaryObject::dtor mActive = 0, this = 00EFF4D7