希望C++高手指教,复制构造函数的疑惑.
专门写了一个简单的实例.便于高手查看.如下
#include <iostream>
using namespace std;
class OBJECT
{
public:
OBJECT(){cout<<"构造函数\n";}
OBJECT(const OBJECT & ob){cout<<"复制构造\n";}
~OBJECT(){cout<<"析构函数\n";} //注释后,会出来两条复制构造函数执行.不注释只有一条.
};
OBJECT func(const OBJECT & ob)
{
return ob;
}
void main()
{
OBJECT a;
OBJECT b=func(a);
}
我把析构函数注释起来.就会出现两次复制构造函数.不注释起来只有一条.怎么也理解不通.
我知道在func函数中ob返回会产生,一个临时对象.在单独为一个对象初始化给另一个对象时,也会调用复制构造函数.此时将func的回返值直接初始化给b使用的应该是同一个临时对象.那么也应该只调用一次复制构造函数.实际中也是如此.但是把析构函数注释起来就会出现两条复制构造函数.实在费解啊.难道编译器自动给出的析构函数和自定义的析构函数在执行时间上有不同?
希望高手详解
[解决办法]
When certain criteria are met, an implementation is allowed to omit the copy construction of a class object,even if the copy constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy operation as simply two different ways of referring to
the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.111) This elision of copy operations is permitted in thefollowing circumstances (which may be combined to eliminate multiple copies):
— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy operation can be omitted by constructing the automatic object directly into the function’s return value
— when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the temporary object directly into the target of the omitted copy
[Example:
- C/C++ code
class Thing {public:Thing();?Thing();Thing(const Thing&);};Thing f() {Thing t;return t;}Thing t2 = f();
[解决办法]
楼主:刚刚翻看了《C++ primer plus第五版》的385页,上面说有4中声明会调用复制构造函数:
- C/C++ code
A x(y);A x = y;A x = A(y);A* pX = new A(y);