use*_*581 58 c++ reset shared-ptr nullptr c++11
我有一个关于C++ 11最佳实践的问题.清除shared_ptr时,我应该使用reset()没有参数的函数,还是应该设置shared_ptr为nullptr?例如:
std::shared_ptr<std::string> foo(new std::string("foo"));
foo.reset();
foo = nullptr;
Run Code Online (Sandbox Code Playgroud)
是否存在任何真正的差异,或者两种方法都存在优势/劣势?
And*_*owl 74
是否存在任何真正的差异,或者两种方法都存在优势/劣势?
在第二种形式(foo = nullptr)是根据第一种形式定义的意义上,这两种选择是绝对等价的.根据C++ 11标准的第20.7.1.2.3/8-10段:
Run Code Online (Sandbox Code Playgroud)unique_ptr& operator=(nullptr_t) noexcept;8 效果:
reset().9 后置条件:
get() == nullptr10 返回:
*this.
因此,只需选择最适合您的意图.就个人而言,我更喜欢:
foo = nullptr;
Run Code Online (Sandbox Code Playgroud)
因为它更明显我们希望指针为null.但是,作为一般建议,请尽量减少需要显式重置智能指针的情况.
此外,而不是使用new:
std::shared_ptr<std::string> foo(new std::string("foo"));
Run Code Online (Sandbox Code Playgroud)
考虑std::make_shared()尽可能使用:
auto foo = std::make_shared<std::string>("foo");
Run Code Online (Sandbox Code Playgroud)
Wal*_*ter 13
我更喜欢reset()它,因为它标志着意图.但是,尝试编写代码,以便您不需要明确清除a shared_ptr<>,即确保shared_ptr<>在您清除它时超出范围.