为什么复制构造函数被调用,即使我实际上正在复制到 C++ 中已经创建的对象?
why copy constructor is getting called even though I am actually copying to already created object in C++?
我写了下面的代码,但我不明白为什么要调用复制构造函数。
#include <iostream>
using namespace std;
class abc
{
public:
abc()
{
cout << "in Construcutor" << (this) << endl;
};
~abc()
{
cout << "in Destrucutor" << (this) << endl;
};
abc(const abc &obj)
{
cout << "in copy constructor" << (this) << endl;
cout << "in copy constructor src " << &obj << endl;
}
abc& operator=(const abc &obj)
{
cout << "in operator =" << (this) << endl;
cout << "in operator = src " << &obj << endl;
}
};
abc myfunc()
{
static abc tmp;
return tmp;
}
int main()
{
abc obj1;
obj1 = myfunc();
cout << "OK. I got here" << endl;
}
当我运行这个程序时,我得到以下输出
in Construcutor0xbff0e6fe
in Construcutor0x804a100
in copy constructor0xbff0e6ff
in copy constructor src 0x804a100
in operator =0xbff0e6fe
in operator = src 0xbff0e6ff
in Destrucutor0xbff0e6ff
OK. I got here
in Destrucutor0xbff0e6fe
in Destrucutor0x804a100
我不明白为什么在我实际分配对象时调用复制构造函数。
如果我在 myfunc()
中声明 abc tmp
而不是 static abc tmp
,则不会调用复制构造函数。任何人都可以帮助我了解这里发生了什么。
因为你return一个对象按值来自myfunc
,这意味着它正在被复制。
如果您不在 myfunc
中创建对象 static
,那么 copy-constructor 不会被调用的原因是 copy elision and return value optimization (a.k.a .RVO)。请注意,即使您的 copy-constructor 可能不会被调用,它仍然必须存在。
我写了下面的代码,但我不明白为什么要调用复制构造函数。
#include <iostream>
using namespace std;
class abc
{
public:
abc()
{
cout << "in Construcutor" << (this) << endl;
};
~abc()
{
cout << "in Destrucutor" << (this) << endl;
};
abc(const abc &obj)
{
cout << "in copy constructor" << (this) << endl;
cout << "in copy constructor src " << &obj << endl;
}
abc& operator=(const abc &obj)
{
cout << "in operator =" << (this) << endl;
cout << "in operator = src " << &obj << endl;
}
};
abc myfunc()
{
static abc tmp;
return tmp;
}
int main()
{
abc obj1;
obj1 = myfunc();
cout << "OK. I got here" << endl;
}
当我运行这个程序时,我得到以下输出
in Construcutor0xbff0e6fe
in Construcutor0x804a100
in copy constructor0xbff0e6ff
in copy constructor src 0x804a100
in operator =0xbff0e6fe
in operator = src 0xbff0e6ff
in Destrucutor0xbff0e6ff
OK. I got here
in Destrucutor0xbff0e6fe
in Destrucutor0x804a100
我不明白为什么在我实际分配对象时调用复制构造函数。
如果我在 myfunc()
中声明 abc tmp
而不是 static abc tmp
,则不会调用复制构造函数。任何人都可以帮助我了解这里发生了什么。
因为你return一个对象按值来自myfunc
,这意味着它正在被复制。
如果您不在 myfunc
中创建对象 static
,那么 copy-constructor 不会被调用的原因是 copy elision and return value optimization (a.k.a .RVO)。请注意,即使您的 copy-constructor 可能不会被调用,它仍然必须存在。