Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 正确使用std::unique_ptr release()作为原始指针函数参数_C++_C++11_Memory Management_Unique Ptr - Fatal编程技术网

C++ 正确使用std::unique_ptr release()作为原始指针函数参数

C++ 正确使用std::unique_ptr release()作为原始指针函数参数,c++,c++11,memory-management,unique-ptr,C++,C++11,Memory Management,Unique Ptr,我正在将子元素添加到父元素。父级的addChildElement()接受一个原始指针(属于我无法更改的库),然后承担所有权并删除 std::unique_ptr<Element> child {new Element}; // ...do things... parent.addChildElement (child.release()); // will be deleted by parent std::unique_ptr child{new Element}; //…做

我正在将子元素添加到父元素。父级的
addChildElement()
接受一个原始指针(属于我无法更改的库),然后承担所有权并删除

std::unique_ptr<Element> child {new Element};

// ...do things...

parent.addChildElement (child.release()); // will be deleted by parent
std::unique_ptr child{new Element};
//…做事。。。
parent.addChildElement(child.release());//将由父级删除

这是正确的现代做法吗?要在最后一刻使用唯一的\u ptr,而不是原始指针?

是的。调用
release
后,唯一指针将释放指向的数据的所有权。现代实践是现代的,因此仍在争论中^^^在您展示的特定案例中,它看起来是指向Me的指针的一个很好的用法什么是
addChildElement
?也许最好使用signature
void addchildelement(std::unique_ptr&&)
而不要使用
release
函数。@ilotXXI“属于一个我无法更改的库”@ilotXXI,如果您可以更改signature(在这种情况下是不可能的)我仍然认为,采用
unique_ptr
实例的值而不是r值引用是解决问题的最佳方法,因为您希望获得所有权。