【发布时间】:2011-08-27 08:24:55
【问题描述】:
这是让我感到困惑的代码:
#include <iostream>
using namespace std;
class B {
public:
B() {
cout << "constructor\n";
}
B(const B& rhs) {
cout << "copy ctor\n";
}
B & operator=(const B & rhs) {
cout << "assignment\n";
}
~B() {
cout << "destructed\n";
}
B(int i) : data(i) {
cout << "constructed by parameter " << data << endl;
}
private:
int data;
};
B play(B b)
{
return b;
}
int main(int argc, char *argv[])
{
#if 1
B t1;
t1 = play(5);
#endif
#if 0
B t1 = play(5);
#endif
return 0;
}
Fedora 15 上的环境是 g++ 4.6.0。 第一个代码片段输出如下:
constructor
constructed by parameter 5
copy ctor
assignment
destructed
destructed
destructed
而第二个片段代码输出为:
constructed by parameter 5
copy ctor
destructed
destructed
为什么第一个例子调用了三个析构函数,而第二个例子只有两个?
【问题讨论】:
-
您希望看到多少个构造函数?如果还不够,请尝试使用
-fno-elide-constructors进行编译,gcc 不会消除它默认执行的一些构造函数调用。
标签: c++ constructor destructor