在构造函数初始化器中传递新对象是明智的还是愚蠢的?
例如:
class Mallard
{
public:
Mallard()
: s(new SomeLargeObject(5)) {}
private:
SomeLargeObject * s;
};
Run Code Online (Sandbox Code Playgroud)
如果您忘记发布的析构函数执行对称删除,则代码示例中没有任何机械损坏.
虽然传统上(更安全,更少样板)你想要的东西
#include <memory>
class Mallard {
std::unique_ptr<SomeLargeObject> that_;
public:
Mullard(): that_(new SomeLargeObject)
{}
// this way you don't need to code the destructor
};
Run Code Online (Sandbox Code Playgroud)
注意:
正如人们在评论中强调的那样(@ Praetorian,@ RemyLebeau,@ AdrianMcCarthy),如果您以这种方式初始化多个成员,那么当从对象构造函数抛出异常时,它不会受到内存泄漏的影响不调用此对象的析构函数.上面提出的语法std::unique_ptr不受此问题的影响(这就是为什么它是安全的).