我在尝试使用从我的 DLL 导出的函数时遇到问题。
我收到一条消息(抱歉,我无法上传图片):
Windows has triggered a breakpoint in LibTester.exe.
This may be due to a corruption of the heap, which indicates a bug in LibTester.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while LibTester.exe has focus.
The output window may have more diagnostic information.
我有一个 Vector 类,带有重载的赋值运算符和一些构造函数:
Vector::Vector() : X(0.0f), Y(0.0f), Z(0.0f) { }
Vector::Vector(const Vector& vector) : X(vector.X), Y(vector.Y), Z(vector.Z) { }
Vector::Vector(float x, float y, float z) : X(x), Y(y), Z(z) { }
.
.
.
Vector& Vector::operator=(const Vector& rhs)
{
this->X = rhs.X;
this->Y = rhs.Y;
this->Z = rhs.Z;
return *this;
}
只有在我尝试将现有 vector 分配给新 vector 时才会出现此问题 由构造函数生成:
Vector v1 = Vector(); //Works
Vector v2 = Vector(1.0f, 1.0f, 1.0f); //Works
v1 = v2; //Works
v1 = Vector(); //Fails
v1 = Vector(1.0f, 1.0f, 1.0f); //Fails
如果这是相关的,Vector struct 派生自 class IPrintable:
class IPrintable
{
public:
~IPrintable()
{
if (this->m_pStr != NULL)
delete[] this->m_pStr;
}
virtual char* ToString() = 0;
protected:
char* m_pStr;
};
有人知道是什么导致了这种行为吗?
最佳答案
如果那是 IPrintable
的完整定义,问题是 m_pStr
是单元化的,这意味着 delete[]
的调用不正确.
这失败了:
v1 = Vector();
因为创建了一个临时的 Vector
并且立即执行了错误的析构函数。要更正初始化 m_pStr
或更好的解决方案是使用 std::string
。如果您必须使用 char*
,那么您还必须实现复制构造函数和赋值运算符或防止复制(参见 What is The Rule of Three?)。
关于c++ - Windows 已触发断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12216694/