存档

文章标签 ‘constructor’

C++拷贝构造函数没有执行的问题

2009年4月29日 没有评论

问题是在这http://lilacbbs.com/forum/d.php?bid=66&id=62395,想了半天想不明白

摘要就是 Fred z = Fred(3);时没有执行拷贝构造函数,查了标准手册才发现原来如此:会不会调用拷贝构造函数由具体编译器实现决定:

Standard C++98 12.8

15 Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the

same cvunqualified

type, an implementation is permitted to treat the original and the copy as two different

ways of referring to the same object and not perform a copy at all, even if the class copy constructor or

destructor have side effects. For a function with a class return type, if the expression in the return statement

is the name of a local object, and the cvunqualified

type of the local object is the same as the function

return type, an implementation is permitted to omit creating the temporary object to hold the function return

value, even if the class copy constructor or destructor has side effects. In these cases, the object is

destroyed at the later of times when the original and the copy would have been destroyed without the optimization.

111) [Example:

class Thing {

public:

Thing();

~Thing();

Thing(const Thing&);

Thing operator=(const Thing&);

void fun();

};

Thing f() {

Thing t;

return t;

}

Thing t2 = f();

Here t does not need to be copied when returning from f. The return value of f may be constructed

directly into the object t2. ]