简体   繁体   English

无法取消引用插入向量中的类对象指针

[英]Cannot Dereference Class Object Pointers Inserted Into a Vector

struct Tree_Node
{
    typedef int node_value_type;

    Tree_Node(node_value_type key) : value(key) {}

public:
    node_value_type value = 0;
    Tree_Node* right = nullptr;
    Tree_Node* left = nullptr;
};

After inserting pointers to the above class into a vector, trying to pop an element and dereference it gives me an ``Access Violation Reading Location'' exception in Visual C++. 将指向上述类的指针插入向量后,尝试弹出一个元素并取消引用它,这使我在Visual C ++中出现``访问冲突读取位置''异常。

vector<Tree_Node*> node_list(2);

Tree_Node* node1 = new Tree_Node(5);

node_list.push_back(node1);

cout << node_list.front()->value;

However, the following works fine: 但是,以下工作正常:

Tree_Node* node2 = node1;

cout << node2->value << endl;

What am I missing out on here? 我在这里错过了什么?

Please note that I am adding and accessing the vector elements inside the same scope. 请注意,我正在同一范围内添加和访问矢量元素。 Additionally, I am also aware of possible memory leaks and cleaning up. 此外,我也意识到可能的内存泄漏和清理。 I just wish to know why the above code isn't working 我只想知道为什么上面的代码不起作用

vector<Tree_Node*> node_list(2);

it creates a vector with two null pointers. 它创建一个带有两个空指针的向量。

node_list.push_back(node1);

it inserts a third element 它插入第三个元素

cout << node_list.front()->value;

it tries to access the first, which is a null pointer 它尝试访问第一个,它是一个空指针


To reserve space without inserting elements use: 要保留空间而不插入元素,请使用:

vector<Tree_Node*> node_list;
node_list.reserve(2);

But I'm almost sure that the default ctor reserves place for more than 2 elements. 但是我几乎可以确定默认的ctor保留了两个以上的元素。

You can also update the two allocated elements: 您还可以更新两个分配的元素:

vector<Tree_Node*> node_list(2);
node_list[0] = node1;
node_list[1] = node2;

And if you want to make sure that your container contains only two elements use an std::pair or (if you can use C++11) an std::array . 如果要确保容器仅包含两个元素,请使用std::pair或(如果可以使用C ++ 11) std::array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM