简体   繁体   English

构造函数中的c ++异常安全性

[英]c++ exception safety in constructor

What about following code 怎么样下面的代码

MyClass a(new Foo(), new Bar());

if "new Foo()" is successful, but "new Bar()" throws, will Foo leak? 如果“new Foo()”成功,但“new Bar()”抛出,Foo会泄漏吗?

Is taking 正在服用

std::unique_ptr<Foo>

or 要么

std::shared_ptr<Foo>

as parameters, enough to prevent the leak? 作为参数,足以防止泄漏?

if "new Foo()" is successful, but "new Bar()" throws, does Foo will leak? 如果“new Foo()”成功,但“new Bar()”抛出,Foo会泄漏吗?

Yes. 是。

Is taking [...] as parameters, enough to prevent the leak? 以[...]为参数,足以防止泄漏?

Not necessarily. 不必要。 It depends on how you pass the parameters. 这取决于您如何传递参数。 For instance, even supposed your class constructor looks like this: 例如,即使你认为你的类构造函数如下所示:

MyClass::MyClass(std::unique_ptr<Foo> foo, std::unique_ptr<Bar> bar)

The following may still cause a leak: 以下可能仍会导致泄漏:

MyClass a(std::unique_ptr<Foo>(new Foo()), std::unique_ptr<Bar>(new Bar())

That is because the compiler may is allowed to evaluate the above expressions in the following order: 这是因为可以允许编译器按以下顺序评估上述表达式:

  1. Evaluate the expression new Foo() 评估表达式new Foo()
  2. Evaluate the expression new Bar() 评估表达式new Bar()
  3. Construct the std::unique_ptr<Foo> temporary from the result of 1. 从结果1构造std::unique_ptr<Foo>临时。
  4. Construct the std::unique_ptr<Bar> temporary from the result of 2. 从结果2构造临时std::unique_ptr<Bar>

If 2) throws an exception, you've lost your Foo . 如果2)抛出异常,你就失去了你的Foo

However, it is possible to make this safe by using std::make_unique<>() (C++14 only) or std::make_shared<>() , like so: 但是,通过使用std::make_unique<>() (仅限C ++ 14)或std::make_shared<>() ,可以使其安全,如下所示:

MyClass a(std::make_unique<Foo>(), std::make_unique<Bar>());

Now no leak could possibly happen, because std::make_unique<>() (and std::make_shared<>() ) immediately associate the object they create to the corresponding smart pointer, without these two operations (dynamic allocation and construction of the smart pointer) being interleaved with any other operation. 现在不会发生泄漏,因为std::make_unique<>() (和std::make_shared<>() )会立即将它们创建的对象关联到相应的智能指针,而不需要这两个操作(动态分配和构造智能指针)与任何其他操作交错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM