C++ 为什么在使用shared_ptr作为函数参数时会出现内存泄漏?

C++ 为什么在使用shared_ptr作为函数参数时会出现内存泄漏?,c++,smart-pointers,C++,Smart Pointers,我读过一本手册,上面说(见): 此外,f(shared_ptr(new int(42)),g()会导致内存泄漏 如果g抛出一个异常。如果共享make_,则不存在此问题 用过 为什么会导致内存泄漏?允许编译器按以下顺序计算该表达式: auto __temp1 = new int(42); auto __temp2 = g(); auto __temp3 = shared_ptr<int>(__temp1); f(__temp3, __temp2); auto\uu temp1=new

我读过一本手册,上面说(见):

此外,
f(shared_ptr(new int(42)),g()
会导致内存泄漏 如果g抛出一个异常。如果共享make_,则不存在此问题 用过


为什么会导致内存泄漏?

允许编译器按以下顺序计算该表达式:

auto __temp1 = new int(42);
auto __temp2 = g();
auto __temp3 = shared_ptr<int>(__temp1);
f(__temp3, __temp2);
auto\uu temp1=newint(42);
自动_temp2=g();
auto _temp3=共享的u ptr(_temp1);
f(uuu temp3,uu temp2);
您可以看到,如果
g()
抛出,则分配的对象永远不会被删除


使用
make_shared
,在分配对象和初始化智能指针以管理对象之间没有任何区别。

+1。是的,这就是原因,我正要写这个,但我先谈到了构造函数,它被搞砸了。