[英]How to handle return-by-value of objects with pointers correctly?
Suppose I have a class Foo
which "has a" single member variable that is a pointer to some other object of Bla
:假设我有一个
Foo
类,它“有一个”单个成员变量,它是指向Bla
其他对象的指针:
struct Foo {
Bla *bla;
Foo() {
this->bla = new Bla();
}
~Foo() {
delete this->bla;
}
};
How do I handle return-by-value of such objects?如何处理此类对象的按值返回?
Foo make_foo() {
return Foo();
}
This creates a new Foo
and Bar
, returns a copy of the created Foo
object including a copy of the internal pointer, and then destructs the local object and with it the Bla
object.这将创建一个新
Foo
和Bar
,返回所创建的副本Foo
对象包括内部指针的副本,然后自毁本地对象,并用它来Bla
对象。 Thus, the following code fails:因此,以下代码失败:
Foo f = make_foo();
std::cout << f.bla << std::endl;
Is this generally considered poor design these days?这些天这通常被认为是糟糕的设计吗?
Should I provide a copy constructor ?我应该提供一个复制构造函数吗? In that case, deep-copying more complex object trees can have severe performance impacts.
在这种情况下,深度复制更复杂的对象树会对性能产生严重影响。
Should I provide a move constructor ?我应该提供移动构造函数吗? Would that handle the
bla
pointer correctly?那会正确处理
bla
指针吗?
Since your class allocates dynamic memory and deallocates the memory in the destructor, follow The Rule of Three .由于您的类分配动态内存并在析构函数中释放内存,因此请遵循三个规则。 Provide a copy constructor and copy assignment operator.
提供复制构造函数和复制赋值运算符。
If you understand move semantics or intend to use rvalue references, provide a move constructor and move assignment operator as well.如果您了解移动语义或打算使用右值引用,请同时提供移动构造函数和移动赋值运算符。 See Rule-of-Three becomes Rule-of-Five with C++11?
看到C++11 的三规则变成五规则了吗? for further details.
了解更多详情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.