访问存储在vector中的指针中的字符串时崩溃
Crash accesing a string inside pointer stored in vector
我无法想象一个单一的原因…这是我的基类
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
继承TextureElementclass 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;
}
相关文章:
- 为什么我的结构在包含字符串时崩溃?
- 当 getline 用于获取整个字符串时,程序崩溃
- 删除动态字符串时程序崩溃
- 当 JSON 值应为 INT 但以字符串类型发送时,RapidJSON 崩溃
- 从数组比较2个字符串时,程序崩溃
- C 通过char读取文件字符串的文件char;崩溃
- 使用字符串而不是字符数组时程序崩溃
- 返回向量<对<字符串,字符串>>会导致 gcc 编译代码 (curlcpp) 崩溃
- 矢量尝试添加字符串时会崩溃
- 从CSV文件读取时,试图将值插入一个字符串中时崩溃
- 清理所拥有的(!)字符串成员时,析构函数偶尔崩溃
- 程序使用SCANF读取字符串时会崩溃
- 在执行字符串时更改字符会使程序崩溃
- 程序在输入 10 个字符串后崩溃
- o字符串流对象创建导致我的程序崩溃
- p = new String [0]和p = new Int [0]之后,为什么当删除[] p时字符串版本崩溃
- C++:使用 LSD 基数排序字符串排序崩溃
- jvm在尝试将TCHAR类型发送到接受字符串作为参数的java函数时崩溃
- va_list值始终为-52,并使用字符串崩溃
- Flex cout字符串崩溃