Seb*_*Bln 4 c++ exception unique-ptr
我偶然发现了这样的代码:
void foo(T* bar); // Note: takes ownership of 'bar'.
foo(new T());
Run Code Online (Sandbox Code Playgroud)
现在我想知道将其重构为是否有任何意义:
void foo(T* bar); // Note: takes ownership of 'bar'.
auto tempT = std::make_unique<T>();
foo(tempT.release());
Run Code Online (Sandbox Code Playgroud)
请注意,不幸的是我无法更改“foo”的签名。
它更安全吗?
不。但是,考虑一个稍微复杂的例子:
auto tempT = std::make_unique<T>();
some_operation();
foo(tempT.release());
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果不使用 unique_ptr,将会存在异常安全的潜在问题。
也就是说,更安全的是:
void foo(std::unique_ptr<T> bar); // no need to note that takes ownership
// because that's implied by the type
Run Code Online (Sandbox Code Playgroud)
请注意,不幸的是我无法更改“foo”的签名。
然后编写一个您可以控制的包装函数。
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |