创建 int 的shared_ptr向量

Create a vector of shared_ptr to ints

本文关键字:ptr 向量 shared int 创建      更新时间:2023-10-16

试图创建 int 到 int 的shared_ptr向量。

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

#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>构造函数标记为显式。 源。您将无法使用原始指针调用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>返回一个类型为 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(...))"中看到此答案的额外分配。