c++ - 为指针 vector 取消引用迭代器时出现段错误

标签 c++ pointers vector dereference

我有一个对象指针 vector

    std::vector<Element*> elements;

当遍历 vector 时,我想对迭代器进行双重解引用,以便调用对象的方法。

    std::cout << (*it)->getName() << std::endl;

这会导致段错误。相关代码如下。

我认为问题在于我如何初始化 vector ,因为我可以将 for 循环移动到方法 initialize() 中并且它工作正常。在 takeTurn() 中, vector 大小合适,指针包含正确的地址。这是否意味着指向的对象被过早销毁?

主要.cpp:

#include <vector>
#include <iostream>
#include "Element.h"

    std::vector<Element*> elements;

void initialize() {
    Element ice = Element("ice",1);
    Element fire = Element("fire",2);
    elements.push_back(&ice); 
    elements.push_back(&fire);
}

void takeTurn() {
    std::vector<Element*>::iterator it;
    for(it = elements.begin(); it != elements.end(); ++it) {
        std::cout << (*it)->getName() << std::endl;
    }
}

int main() {
    initialize();
    takeTurn();
    return 0;
}

元素.h:

#include <string>

class Element {
    public:
        Element(std::string name, int id);
        int getID() { return id_; }
        std::string getName() { return name_; }

    private:
        int id_;
        std::string name_;
};

元素.cpp:

#include "Element.h"

Element::Element(std::string name, int id) {
    name_ = name;
    id_ = id;
}

最佳答案

你的初始化函数坏了。您创建本地对象,然后将它们的地址推送到 vector 中。但是当函数返回时,那些对象被销毁,指针不再有效。除非您需要多态性,否则最简单的解决方法就是创建一个 Element 对象的 vector ,而不是指针。

std::vector<Element> elements;
...
elements.push_back(Element("ice",1));
elements.push_back(Element("fire",2));

如果需要多态,就用智能指针。

std::vector<std::unique_ptr<Element>> elements;
...
elements.push_back(std::unique_ptr<Element>(new Element("ice",1)));
elements.push_back(std::unique_ptr<Element>(new Element("fire",2)));

如果您要继续使用原始指针,那么您将需要一些方法来确保对象的持久性,可能是通过使用 new 分配它们。然后,您需要确保对每个已完成的指针调用 delete。我不推荐这条路线。

关于c++ - 为指针 vector 取消引用迭代器时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010562/

相关文章:

C++ 如何求解非常大的稀疏线性系统

c++ - 跳过元素缓冲区中的索引

c++ - Const 与 C++ 中的智能指针

c++ - 一个变量中的最大指针数

c++ - 无法理解工作代码和损坏代码之间的区别

c++ - 读/写文件,字节丢失,可能是字符溢出

r - 当start大于stop时如何生成序列

c++ - Windows - 了解外部 Window 移动

c - 调用 yylex() 后全局指针设置为 NULL

R,X的所有元素是否都存在于Y中