创建一个shared_ptr向量的向量

kmi*_*las 3 c++ smart-pointers shared-ptr c++11

尝试创建shared_ptr到int的向量.

我哪里错了?谢谢.基思:^)

#include <iostream>
#include <vector>
#include <memory>

int main() {
    std::vector<std::shared_ptr<int> > w;
    std::vector<std::shared_ptr<int> >::iterator it_w;
    w.push_back(new int(7));

    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

编译结果:

pickledegg> g++ -std=c++11 -o shared_ptr shared_ptr.cpp
shared_ptr.cpp:29:4: error: no matching member function for call to 'push_back'
        w.push_back(new int(7));
        ~~^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:697:36: note: 
      candidate function not viable: no known conversion from 'int *' to 'const value_type' (aka
      'const std::__1::shared_ptr<int>') for 1st argument
    _LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);
                                   ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:699:36: note: 
      candidate function not viable: no known conversion from 'int *' to 'value_type' (aka
      'std::__1::shared_ptr<int>') for 1st argument
    _LIBCPP_INLINE_VISIBILITY void push_back(value_type&& __x);
                                   ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

Fra*_*eux 9

std::shared_ptr<T>接受原始指针的构造函数被标记为显式.来源.您将无法调用push_back与原始指针,因为它不是隐式转换为std::shared_ptr<int>这正是push_back需要作为参数.解决方案是使用emplace_back代替push_back或使用std::make_shared<int>.

emplace_back 匹配给予T的构造函数之一的参数.

w.emplace_back(new int(7));
Run Code Online (Sandbox Code Playgroud)

std::make_shared<int>返回一个类型的对象std::shared_ptr<int>,避免这个问题.

w.push_back(std::make_shared<int>(7));
Run Code Online (Sandbox Code Playgroud)

您可以组合这些解决方案.

#include <iostream>
#include <vector>
#include <memory>

int main(int argc, char** argv) {
    std::vector<std::shared_ptr<int> > w;
    std::vector<std::shared_ptr<int> >::iterator it_w;
    w.emplace_back(std::make_shared<int>(7));

    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

编辑:作为一个附加的注释,总是喜欢std::make_shared<T>(...)std::shared_ptr<T>(new T(...)).它旨在避免非常微妙的潜在内存泄漏.它还优雅地避免了new没有delete它可能会打扰某些人的情况.

编辑2:此外,它std::make_shared<T>(...)有一个性能优势,它避免在`std :: shared_ptr(new T(...))中的额外分配' 看到这个答案.

  • `emplace_back(std::make_shared&lt;int&gt;(7))` 调用了 `std::shared_ptr` 的 copy-ctor,这有点笨拙,因为 emplace_back 可以解决这个问题。 (2认同)