c++ 对象复制引用时何时调用构造函数、析构函数

class TEST{
private : public :
TEST() {std::cout << "constructor" << std::endl; }
~TEST() {std::cout << "destructor" << std::endl; } }; class TEST fun(void)
{
TEST t, tt; return t;
} int main()
{ class TEST t = fun(); std::cout << "test...test" << std::endl; }

$ ./pointer_reference
constructor
constructor
destructor
test...test
destructor //main函数中创建 t 实际上就是复制

class TEST{
private : public :
TEST() {std::cout << "constructor" << std::endl; }
~TEST() {std::cout << "destructor" << std::endl; } }; class TEST fun(void)
{
TEST t; TEST tt = t; return t;
} int main()
{ class TEST t = fun(); std::cout << "test...test" << std::endl; }

$ ./pointer_reference
constructor
destructor  //创建tt时候没有调用构造函数
test...test
destructor  //t 最后被释放

class TEST{
private : public :
TEST() {std::cout << "constructor" << std::endl; }
~TEST() {std::cout << "destructor" << std::endl; } }; #if 0 //case 0
void fun(class TEST t)
#else //case 1
void fun(class TEST& t)
#endif
{
return;
} int main()
{
class TEST t; fun(t); std::cout << "test...test" << std::endl; }

case 0:

$ ./pointer_reference
constructor
destructor
test...test
destructor

case 1:

$ ./pointer_reference
constructor
test...test
destructor

上一篇:Bitnami WordPress无法修改MySQL root的默认密码的解决方法?


下一篇:android模拟器不能用键盘