AMC*_*der 2 c++ optimization constructor copy-elision
以下代码不会调用复制构造函数.
struct X
{
int x;
X(int num)
{
x = num;
std::cout << "ctor" << std::endl;
}
X(const X& other)
{
std::cout << "copy ctor" << std::endl;
}
};
int main(int argc, _TCHAR* argv[])
{
X* x = new X(3);
X* y(x);
}
Run Code Online (Sandbox Code Playgroud)
输出:
ctor
Run Code Online (Sandbox Code Playgroud)
是复制品吗?
代码
X* x = new X(3);
X* y(x);
Run Code Online (Sandbox Code Playgroud)
是不一样的
X x(3);
X* y = new X(x);
Run Code Online (Sandbox Code Playgroud)
你不是在复制对象,而是指针.之后X* y(x);,两个指针都将指向同一个对象.