2012年(158)
分类: C/C++
2012-11-20 10:21:18
先看一段代码:
#include
using namespace std;
class foo{
public:
foo() { cout<<"default constructor
calling."<
foo bar()
{
foo t;
return t;
}
int main(void)
{
{
foo a = bar();
// gcc3.4.2中
// default
constructor calling.
// destructor calling.
//
VC2005(77626-009-0000007-41837)中
// default constructor
calling.
// copy constructor calling.
// destructor
calling.
// destructor calling.
}
cout <<
"--------" << endl;
{
foo b;
b =
bar();
// gcc3.4.2中
// default constructor
calling.
// default constructor calling.
// assigned
operator calling.
// destructor calling.
// destructor
calling.
// VC2005(77626-009-0000007-41837)中
// default
constructor calling.
// default constructor calling.
// copy constructor calling.
// destructor calling.
// assigned operator calling.
// destructor calling.
// destructor calling.
}
return 0;
}
问题就在
foo bar()
{
foo t;
return
t;
}
中,return t 时调不调用拷贝构造函数? 更一般的说,在最近的C++标准中,具名对象(且这个对象有side
effects用途时)返回时应不应该优化?
争论太多了,留在这里“秋后问斩”^_^
网友评论2012-11-20 10:23:42
abcs
我问的正是"C++ standard"。MS的文章里面有一句:
The C++ standard allows the elision of the copy constructor (even if this results in different program behavior), which has a side effect of enabling the compiler to treat both objects as one (see section 12.8. Copying class objects, paragraph 15; see Reference).
Reference
The C++ Standard Incorporating Technical Corrigendum 1 BS ISO/IEC 14882:2003 (Second Edition)
说的就是这个事情么?
网友评论2012-11-20 10:23:26
abcs
是标准允许这么优化么?
http://msdn.microsoft.com/visualc/default.aspx?pull=/library/en-us/dnvs05/html/nrvo_cpp05.asp