创建 int 的shared_ptr向量
Create a vector of shared_ptr to ints
试图创建 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(...))"中看到此答案的额外分配。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 为共享 ptr 向量实现复制 c'tor?
- 对唯一 ptr 无效读取的引用向量
- 接口 PTR 的返回向量C++
- 如何在满足谓词的向量中获得唯一PTR的子集
- 通过成员函数将唯一 ptr 的向量附加到另一个向量
- C++ 提升克隆 PTR 向量
- PTR到结构体和PTR到结构体的向量的模板方法专门化