现代c ++中的独特指针

use*_*884 3 c++ pointers

我在网上搜索了很多,并unique_ptr在现代c ++中找到了很多不同的实现示例.我已经开始更新我的所有代码开始::iterators进入auto等等.然而,有了智能指针我不认为我完全理解我想要做的事情.

使用标准指针,我有:

 object *temp = new object();
Run Code Online (Sandbox Code Playgroud)

然后使用新的智能指针我:

  unquie_ptr<object> temp(new object());
Run Code Online (Sandbox Code Playgroud)

这不是正确的实施方式吗?如果是这样的话,当我在程序结束时构建一个简单的清理函数时,似乎更多的输入/工作来制作智能指针?

dlm*_*tei 7

你可以使用更高性能std::make_uniquestd::make_shared.

但是,make_unique在C++ 11中不可用,但在C++ 14及更高版本中

所以

std::unique_ptr<object> = std::make_unique<object>();
Run Code Online (Sandbox Code Playgroud)

要么

auto p = std::make_unique<object>();
Run Code Online (Sandbox Code Playgroud)

和类似的事情一样shared_ptr.

在C++ 11中,您可以使用表达式unique_ptr.

unquie_ptr<object> temp(new object());
Run Code Online (Sandbox Code Playgroud)

  • `make_unique`在`C++ 14`中引入.`make_shared`已在`C++ 11`中引入. (2认同)