An MSDN page about smart pointers包括关于在参数列表中创建智能指针的升级警告:
Always create smart pointers on a separate line of code, never in a parameter list, so that a subtle resource leak won’t occur due to certain parameter list allocation rules.
它所指的参数列表分配规则是什么?什么情况下会发生资源泄露?
最佳答案
这是指以不同顺序评估参数的可能性,例如
func(unique_ptr<MyClass>(new MyClass), a(), b());
如果评估顺序是:a()
, MyClass()
, b()
,然后 unique_ptr
已构建,可能会发生 b()
throws 和内存将被泄漏。
使用 make_unique
的保护措施(已在 C++14 中添加,而且效率更高) (假设 MSVC 并根据您的编译器版本,您可能必须自己定义一个或 take a look here )。这同样适用于 shared_ptr
.
看看at the notes for std::make_shared here ,也:
Moreover, code such as
f(std::shared_ptr<int>(new int(42)), g())
can cause a memory leak ifg
throws an exception becauseg()
may be called afternew int(42)
and before the constructor ofshared_ptr<int>
. This doesn't occur inf(std::make_shared<int>(42), g())
, since two function calls are never interleaved.
关于c++ - 智能指针和参数列表分配规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019249/