c++ - 智能指针和参数列表分配规则

标签 c++ c++11 smart-pointers

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 if g throws an exception because g() may be called after new int(42) and before the constructor of shared_ptr<int>. This doesn't occur in f(std::make_shared<int>(42), g()), since two function calls are never interleaved.

关于c++ - 智能指针和参数列表分配规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019249/

相关文章:

c++ - boost::spirit 语义 Action :发出结果

c++ - 继承或组合 : Rely on "is-a" and "has-a"?

C++ "smart pointer"自动转换为裸指针但不能显式删除的模板

c++ - 具有 std::unique_ptr 的容器的访问器函数

c++ - 我应该使用智能指针吗?

c++ - 弹性和 Bison : parse string without quotes

c++ - 如何在编译时检查两种类型是否相同(如果它与 Boost strong typedef 一起使用则加分)

C++11 基于范围的 for() 循环评估一次或多次?

c++ - 当永远不会同时访问共享托管对象时,在生产者和消费者之间使用 std::shared_ptr 是否安全?

python - 构建使用 C++11 功能的 Python 扩展时出现问题