访问存储在vector中的指针中的字符串时崩溃

Crash accesing a string inside pointer stored in vector

本文关键字:字符串 崩溃 指针 存储 vector 访问      更新时间:2023-10-16

我无法想象一个单一的原因…这是我的基类

class TextureElement
{
public:
    TextureElement(std::wstring mname);
    std::wstring file;
    std::wstring name;
    TexMode texmode;
};

这是一个基本用法:

TextureElement* textureElement = new TextureElement(prename);
mClass->textures.push_back(textureElement);
textureElement->file = path;//<<here crashes if inheritance is done

显然prename和path是wstring, mstruct mClass包含几个向量,包括这个存储TextureElement* type

这个可以工作但是如果我从Element

继承TextureElement
class Element
{
public:
    Element(std::wstring mname, ElementType t);
    Element(){};
    ~Element();
    ElementType type;
    std::wstring name;
}; 

它崩溃。

我已经尝试实现复制方法的TextureElement(我几乎肯定这是不必要的),但它没有工作。对此有什么想法吗?提前谢谢大家

如果您从Element继承,您可能希望声明一个 virtual析构函数以进行适当的清理:

virtual ~Element() {}

此外,在std::vector中放置原始所属指针时要注意。考虑一个由智能指针组成的向量,比如vector<unique_ptr<T>>vector<shared_ptr<T>>


编辑

这段代码编译得很好,似乎可以工作(在VS2015更新3上测试):

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
enum class ElementType
{
    Texture,
    Foo,
    Bar
};
class Element
{
public:
    Element(const wstring& name, ElementType type) 
        : Name(name), Type(type)
    {}
    virtual ~Element() {}
    ElementType Type;
    wstring Name;
};
class TextureElement : public Element
{
public:
    explicit TextureElement(const wstring &name)
        : Element(name, ElementType::Texture)
    {}
    wstring File;
};
int main()
{
    vector<shared_ptr<Element>> v;
    auto p = make_shared<TextureElement>(L"Test");
    v.push_back(p);
    p->File = L"C:\Some\File";
    wcout << p->File;
}