求教:C++复制控制问题。。。求教各路神仙
一个简单的类:
class TestObj {
public:
TestObj();
TestObj(const TestObj& obj);
string str;
};
TestObj::TestObj() {
str = "hello";
cout << "create-->" << this << endl;
}
TestObj::TestObj(const TestObj& obj) {
str = obj.str;
cout << "copy-->" << str << endl;
}
测试代码:
TestObj test() {
TestObj o;
return o;
}
int main() {
TestObj o2 = test();
cout << &o2;
}
输出结果:
create-->0x28fef0
0x28fef0
请问:为什么没有调用copy构造,为什么输出的内存地址是一样的。。
[解决办法]
代码应该没什么问题。事实上,用函数返回值对xx赋值是应该调用拷贝构造函数的,可能是编译器做了优化。编译器经常会做这样的优化。
我用VS测试了下,的确输出:
create-->0014FAF4
copy-->hello
0014FC10
void cp_test(TestObj obj){
}
cp_test(o2);