将共享指针推回向量时出错
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));
^
我对指针的了解有限,我无法找出错误。请帮助
编辑
根据下面给出的答案并通过 google 搜索,我得出结论,指针向量不是一个好主意。但在我的例子中,只有必要让我使用指针向量。我正在使用 C++ 进行科学计算,节点对象包含我需要计算的变量。由于节点对象数量多,每次复制和移动都比较困难。因此,为了传入函数和初始化其他 class 对象,我需要使用指向节点或引用的指针。
如果 shared_ptr
在我的上下文中是错误的选择,是否还有其他简单有效的方法可以做到这一点?由于我是 C++ 的初学者,我更喜欢一个简单的解决方案。
接受一个Y*
的shared_ptr
constructor是explicit
。它不会作为用户定义的转换参与将原始指针转换为 shared_ptr
。并且 temp.push_back
没有超载以接受原始指针。因此你的错误。
您 可以 消除 compile-time 错误,但是当 temp
中的 shared_ptr
时您的程序将表现出未定义的行为将开始对 m_nodes
.
拥有的对象调用 delete
并且使用宏是可怕的。使用类型别名:
using node_ptr = std::shared_ptr<node>;
因为您似乎需要 non-owning 指针(shared_ptr
用于复杂的所有权语义)。传递一个原始指针向量是完全没问题的。在您的情况下,只需将类型别名设置为:
using node_ptr = node*;
这将正确更改语义,而无需重写整个代码。
你不能push_back
一个指向智能指针向量的指针,你应该使用emplace_back()
来构造一个共享指针in-place:
// 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>
看看下面的代码片段。
#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));
^
我对指针的了解有限,我无法找出错误。请帮助
编辑
根据下面给出的答案并通过 google 搜索,我得出结论,指针向量不是一个好主意。但在我的例子中,只有必要让我使用指针向量。我正在使用 C++ 进行科学计算,节点对象包含我需要计算的变量。由于节点对象数量多,每次复制和移动都比较困难。因此,为了传入函数和初始化其他 class 对象,我需要使用指向节点或引用的指针。
如果 shared_ptr
在我的上下文中是错误的选择,是否还有其他简单有效的方法可以做到这一点?由于我是 C++ 的初学者,我更喜欢一个简单的解决方案。
接受一个Y*
的shared_ptr
constructor是explicit
。它不会作为用户定义的转换参与将原始指针转换为 shared_ptr
。并且 temp.push_back
没有超载以接受原始指针。因此你的错误。
您 可以 消除 compile-time 错误,但是当 temp
中的 shared_ptr
时您的程序将表现出未定义的行为将开始对 m_nodes
.
delete
并且使用宏是可怕的。使用类型别名:
using node_ptr = std::shared_ptr<node>;
因为您似乎需要 non-owning 指针(shared_ptr
用于复杂的所有权语义)。传递一个原始指针向量是完全没问题的。在您的情况下,只需将类型别名设置为:
using node_ptr = node*;
这将正确更改语义,而无需重写整个代码。
你不能push_back
一个指向智能指针向量的指针,你应该使用emplace_back()
来构造一个共享指针in-place:
// 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>