创建一个 shared_ptr 到整数的向量

Create a vector of shared_ptr to ints

正在尝试创建一个 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;
}

编译结果:

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.

接受原始指针的std::shared_ptr<T>构造函数被标记为显式。 source。您将无法使用原始指针调用 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));

std::make_shared<int> returns 一个 std::shared_ptr<int> 类型的对象,避免了这个问题。

w.push_back(std::make_shared<int>(7));

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

#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;
}

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

编辑 2:此外,std::make_shared<T>(...) 具有性能优势,它避免了在 `std::shared_ptr(new T(...))' see this answer 中的额外分配.