将共享指针推回矢量时出错

Error when a shared pointer is pushed back into a vector

本文关键字:出错 共享 指针      更新时间:2023-10-16

查看以下代码片段。

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