考虑以下代码。在list1
中,我将保存在堆上的元素添加到矢量和打印。它像预期的那样工作。在list2
中,我从一个函数中添加元素到向量上,该函数也在堆上分配元素。
我知道我必须在addNode
的堆上分配Node
,否则当函数返回时它将被释放。然而,通过最后的print语句,我可以看到堆上的节点仍然被分配,但它们没有显示在我的向量中。
#include <iostream>
#include <vector>
using namespace std;
/*
Simple node class for demo
*/
class Node
{
public:
string val;
Node(string value) { this->val = value; }
};
Node *addNode(vector<Node *> list)
{
// allocate space for node on the heap so it isn't destroyed after function returns
auto node = new Node("foo");
// add pointer to node onto vector
list.push_back(node);
return node;
}
/*
Simple function for printing vector contents
*/
template <typename T>
void printVector(T d)
{
cout << "Vector has size " << d.size() << " and elements: ";
for (auto p = d.begin(); p < d.end(); p++)
{
cout << (*p)->val << ",";
}
cout << "n";
}
int main()
{
// make a new vector
vector<Node *> list1;
// add elements allocated on the heap
list1.push_back(new Node("foo"));
list1.push_back(new Node("foo"));
list1.push_back(new Node("foo"));
printVector(list1); // prints: "Vector has size 3 and elements: foo,foo,foo,"
// make a new vector
vector<Node *> list2;
// add elements allocated on the heap from a function
addNode(list2);
addNode(list2);
// save one of the nodes to a variable for demonstration
auto node = addNode(list2);
printVector(list2); // prints: "Vector has size 0 and elements:"
cout << node->val << "n"; // prints: "foo"
return 0;
}
有人可以解释如何从函数添加元素到向量吗?
在addNode()
中,您通过值传递vector
,因此对调用方的vector
进行复制,然后将Node*
添加到副本中,原始vector
不受影响。
您需要通过引用传递vector
而不是:
Node* addNode(vector<Node*> &list)
与printVector()
相同。您通过值传递vector
,您只是不修改副本,但您仍然应该通过(const)引用传递vector
,以避免完全复制:
template <typename T>
void printVector(const T &d)
附带说明,您正在泄漏您创建的Node
s。当你完成使用它们时,你需要delete
它们:
int main()
{
vector<Node*> list1;
list1.push_back(new Node("foo"));
list1.push_back(new Node("foo"));
list1.push_back(new Node("foo"));
printVector(list1);
for(auto *p : list1)
delete p;
vector<Node*> list2;
addNode(list2);
addNode(list2);
auto node = addNode(list2);
printVector(list2);
cout << node->val << "n";
for(auto *p : list2)
delete p;
return 0;
}
最好使用std::unique_ptr
为您管理:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
...
Node* addNode(vector<unique_ptr<Node>> &list)
{
list.push_back(make_unique<Node>("foo"));
return list.back().get();
}
template <typename T>
void printVector(const T &d)
{
cout << "Vector has size " << d.size() << " and elements: ";
for (const auto &p : d)
{
cout << p->val << ",";
}
cout << "n";
}
int main()
{
vector<unique_ptr<Node>> list1;
list1.push_back(make_unique<Node>("foo"));
list1.push_back(make_unique<Node>("foo"));
list1.push_back(make_unique<Node>("foo"));
printVector(list1);
vector<unique_ptr<Node>> list2;
addNode(list2);
addNode(list2);
auto node = addNode(list2);
printVector(list2);
cout << node->val << "n";
return 0;
}