【发布时间】:2012-05-11 12:30:53
【问题描述】:
我试图了解这种分配在 c++ 中是如何工作的:
Test other = toto();
这是完整的代码源:
#include <iostream>
class Test
{
public:
Test()
{
j = i++;
std::cout<<"default constructor "<<j<<std::endl;
}
Test(const Test&)
{
std::cout<<"constuctor by copy "<<j<<std::endl;
}
Test & operator=(const Test&)
{
std::cout<<"operator = "<<j<<std::endl;
return *this;
}
int j;
static int i;
};
int Test::i = 0;
Test toto()
{
Test t;
return t;
}
int main()
{
Test other = toto();
std::cout<<other.j<<std::endl;
Test another;
return 0;
}
代码没有通过复制或操作符=使用构造函数,所以我真的不明白它是如何工作的...... 我用的是 gcc 4.7.0
感谢您的帮助:)
杰罗姆
【问题讨论】:
-
@jrok - 从常见问题解答中“他们的一位工程师告诉我,他们发现这种按值返回的优化非常快,即使您没有在打开优化的情况下进行编译,您也可以得到它“所以显然这不一定是真的。它可能因编译器而异。
-
@Benj 确实,在尝试使用 gcc 时,即使没有优化也没有副本。
标签: c++ allocation