我想了解何时调用复制构造函数或赋值。假设如下:
class Foo {
public:
Foo()
{
cout << "foo constructor " << this << endl;
test_ = 44;
}
Foo(const Foo& f)
{
cout << "foo copy constructor " << this << endl;
test_ = 55;
}
Foo& operator=(const Foo& other)
{
cout << "foo copy assignment " << this << endl;
return *this;
}
Foo& operator=(Foo& other)
{
cout << "foo copy non-const assignment " << this << endl;
return *this;
}
~Foo() { cout << "foo destructor " << this << endl; };
int bar() const {
cout << "bar call " << this << endl;
return 6;
}
int test_;
};
class Model {
public:
Model()
{
foo_ = std::make_unique<Foo>();
}
Foo get_foo()
{
return *foo_;
}
std::unique_ptr<Foo> foo_;
};
int main() {
cout << "start test 1" << endl;
{
Model model;
Foo foo1 = model.get_foo();
foo1.bar();
}
cout << "end test 1" << endl << endl;
cout << "start test 2" << endl;
{
Model model;
const Foo& foo2 = model.get_foo();
foo2.bar();
}
cout << "end test 2" << endl;
cout << "start test 3" << endl;
{
Model model;
model.get_foo().bar();
}
cout << "end test 3" << endl;
return 0;
}
最后提供输出。
get_foo().bar()
的具体步骤是什么?我希望您能在代码中注意到任何类型的信息/问题(例如 get_foo() 取消引用唯一指针这一事实)。
start test 1
foo constructor 000001D4EF9B6720
foo copy constructor 00000058BED6FA94
bar call 00000058BED6FA94
foo destructor 00000058BED6FA94
foo destructor 000001D4EF9B6720
end test 1
start test 2
foo constructor 000001D4EF9B6F60
foo copy constructor 00000058BED6FAF4
bar call 00000058BED6FAF4
foo destructor 00000058BED6FAF4
foo destructor 000001D4EF9B6F60
end test 2
start test 3
foo constructor 000001D4EF9B6F60
foo copy constructor 00000058BED6FBF4
bar call 00000058BED6FBF4
foo destructor 00000058BED6FBF4
foo destructor 000001D4EF9B6F60
end test 3