【发布时间】:2020-09-11 21:46:52
【问题描述】:
我正在尝试构建一个模板类,该类包含一个指向向量的指针,该向量本身包含指针。
template <typename S, typename T>
struct MyClass
{
std::shared_ptr<aNode<S,T>> head{nullptr};
std::shared_ptr<std::vector<aNode<S,T>>> positionList; // <<- This guy
void add(S const & k, T const & v)
{
std::shared_ptr<aNode<S,T>> newNode = std::make_shared<aNode<S,T>>();
newNode->set_data(k, v);
if (head == nullptr) {
head = newNode;
} else {
auto current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
positionList->push_back(newNode); // <<- Error here
}
[...]
在第 20 行,编译器抛出错误 No matching member function for call to 'push_back'。
现在 -> 运算符应该让我可以访问向量,并且向量当然有一个 push_back 方法。我唯一能想到的是向量没有初始化。
将第 4 行更改为 std::shared_ptr<std::vector<aNode<S,T>>()> positionList; 会引发错误
Member reference base type 'std::__1::shared_ptr<std::__1::vector<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> >, std::__1::allocator<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> > > > ()>::element_type' (aka 'std::__1::vector<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> >, std::__1::allocator<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> > > > ()') is not a structure or union
(仍在第 20 行)。
我哪里错了?
【问题讨论】:
-
请在问题中包含minimal reproducible example
-
positionlist是指向节点向量的共享指针,但您尝试将共享指针推回不适合的节点 -
newNode的类型为std::shared_ptr<aNode<S,T>>,但您的向量存储aNode<S,T>。 -
而
std::shared_ptr<std::vector<aNode<S,T>>()>是错误的。要在shared_ptr中初始化空向量,只需在构造函数中使用std::make_shared()。 -
你真的想要向量上的指针,你分享吗?
std::vector通常就足够了。
标签: c++ pointers templates shared