[英]Extra destructor in Constructor, Copy constructor, Destructor sequence in C++
I am learning C++ and am new to StackOverflow. 我正在学习C ++,并且是StackOverflow的新手。 For a test code, I am observing an extra destructor call relative to what I was expecting.
对于测试代码,相对于我的期望,我观察到了一个额外的析构函数调用。 Below is the code followed by my expected output followed by the actual output.
下面是代码,然后是我的预期输出,然后是实际输出。
Code: 码:
#include <iostream>
class c_Test {
public:
c_Test() { std::cout << "Constructor" << std::endl; }
c_Test(const c_Test& x_in) { std::cout << "Copy constructor" << std::endl; }
c_Test operator= (const c_Test&) { std::cout << "operator =" << std::endl; }
~c_Test() { std::cout << "Destructor" << std::endl; }
};
int main()
{
c_Test t0, t1; // call constructor, constructor
c_Test t2 = t0; // call copy constructor
t0 = t1; // call operator=
return 0; // should call destructor, destructor, destructor
}
I expected the output to be: 我期望输出为:
Constructor
Constructor
Copy constructor
operator =
Destructor
Destructor
Destructor
What I get after compiling and running the program: 编译并运行程序后,我得到的是:
Constructor
Constructor
Copy constructor
operator =
Destructor
Destructor
Destructor
Destructor
I expected every destructor to be paired with a constructor but that is not the case. 我希望每个析构函数都与一个构造函数配对,但事实并非如此。 Why is there an extra Destructor?
为什么会有额外的析构函数?
Your operator=
declares a return type but doesn't return anything; 您的
operator=
声明了返回类型,但不返回任何内容; this causes undefined behavior. 这会导致不确定的行为。 If you change it to
如果您将其更改为
c_Test &operator= (const c_Test&) {
std::cout << "operator =" << std::endl;
return *this;
}
then you get the behavior you expect. 那么您将获得预期的行为。
Side note: This is outside the language specification and as such not dependable, but it seems reasonable to suspect that your compiler inserts a destructor call because the operator=
you declared looks from the outside as though it returned a temporary value (ie, as though it had constructed an object that required destruction), and that no corresponding constructor call is inserted because the operator=
doesn't make good on this promise of its declaration. 旁注:这在语言规范之外,因此也不可靠,但是怀疑编译器插入了析构函数调用似乎是合理的,因为您声明的
operator=
从外部看起来好像它返回了一个临时值(即,好像它构造了一个需要销毁的对象),并且没有插入任何对应的构造函数调用,因为operator=
不能满足其声明的承诺。
Indeed, just declaring the operator=
as returning a reference and not inserting the return
statement makes the code, compiled with gcc 4.9 (without optimizations), show the expected behavior. 确实,仅将
operator=
声明为返回引用,而不插入return
语句,可使使用gcc 4.9编译的代码(无优化)显示预期的行为。 Compiled with clang it crashes, as is its right. 用clang编译时会崩溃,这是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.