将共享指针推回矢量时出错
Error when a shared pointer is pushed back into a vector
查看以下代码片段。
#typedef std::shared_ptr<node> node_ptr;
std::vector<node_ptr> temp;
for(int i=0; i<4; i++)
{
temp.push_back(&m_nodes.at(n[i]-1)) // Got error in this line
}
m_nodes
被定义为节点对象的向量。
std::vector<node> m_node;
当我评估此代码时,出现以下错误:
error: no matching function for call to 'std::vector<std::shared_ptr<node> >::push_back(__gnu_cxx::__alloc_traits<std::allocator<node> >::value_type*)'
temp.push_back(&m_nodes.at(n[i]-1));
^
我对指针的了解有限,我无法找出错误。请帮忙
编辑
从下面给出的答案和谷歌搜索中,我得出的结论是指针向量是一个坏主意。但就我而言,只有必要性使我使用指针向量。我正在使用C++进行科学计算,节点对象包含我需要计算的变量。由于节点对象数量很大,因此很难每次都复制和移动。因此,为了传递到函数和初始化其他类对象,我需要使用指向节点或引用的指针。
如果在我的上下文中shared_ptr
是一个错误的选择,那么还有其他简单有效的方法可以做到这一点吗?由于我是C++初学者,我更喜欢一个简单的解决方案。
接受
Y*
的shared_ptr
构造函数是explicit
。它不会作为用户定义的转换参与将原始指针转换为shared_ptr
。而且temp.push_back
不会重载以接受原始指针。因此你的错误。
您可以使编译时错误消失,但是当temp
中的shared_ptr
将开始对m_nodes
拥有的对象调用delete
时,您的程序将表现出未定义的行为。
使用宏是可怕的。使用类型别名:
using node_ptr = std::shared_ptr<node>;
由于您似乎需要非拥有指针(shared_ptr
用于复杂的所有权语义)。传递原始指针的向量是完全可以的。在您的情况下,只需将类型别名设为:
using node_ptr = node*;
这将正确更改语义,而无需重写整个代码。
不能将
指针push_back
到智能指针的向量中,应改用emplace_back()
就地构造共享指针:
// this will create a new shared_ptr in-place, and will call the appropriate constructor for it.
temp.emplace_back(&m_nodes.at(n[i]-1));
此外,您应该使用 typedef 而不是宏:
typedef std::shared_ptr<node> node_ptr;
// or, better yet:
using node_ptr = std::shared_ptr<node>
相关文章:
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- 在另一台 PC 上执行程序时加载 SDL2 共享库时出错
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 加载共享库时出错:libbsoncxx.so._noabi:无法打开共享对象文件:没有此类文件或目录
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 交叉编译 qt:加载共享库时出错
- 如何与他人共享我的 SFML 游戏而不会出错?
- 加载共享库时出错:JVM.dll
- C++ Linux 加载共享库时出错“未定义的符号:pthread_create”
- 尝试使用共享库部署QT应用程序时出错
- 加载共享库时出错:无法在外部硬件上打开共享对象文件:
- 将共享指针推回矢量时出错
- 编译共享对象时出错:未检测到C++类定义
- 加载共享库时出错:libQt5Multimedia.so.5:无法打开共享对象文件:没有这样的文件或目录
- 加载共享库时出错:libsystemc-2.3.0.so
- 试图编译使用共享库的C++程序时出错
- 链接到链接到另一个共享库的共享库会在退出时出错
- 编译SFML 2.0项目时加载共享库时出错
- 在64位Ubuntu 12.04上运行aapt:加载共享库时出错:libc++.所以:没有这样的文件或目录
- C/C++ 尝试创建共享库时出错.创建库的静态版本时不会发生错误