【发布时间】:2021-03-06 12:08:27
【问题描述】:
我通过简单地创建指定类的实例在程序的最后遇到了这个运行时异常,所以我认为问题出在构造函数、复制构造函数、复制赋值运算符或析构函数上。在我有限的 cpp 知识范围内,我已经阅读并遵循了三法则。
来源.cpp
#include "Header.h"
#include <iostream>
using namespace std;
int main() {
string command = "CREATE TABLE table_name IF NOT EXISTS ((column_1_name,type,default_value), (column_2_name,type,default_value))";
string columns[20] = { "column_1_name,type,default_value", "column_1_name,type,default_value" };
string commandData[9] = { "table_name", "IF NOT EXISTS" };
CommCREATETABLE comm(command, columns, commandData, 2, 2);
}
Header.h 中的相关代码
class CommCREATETABLE {
string fullCommand = "";
string* columns = nullptr;
string* commandData = nullptr;
string tableName = "";
int nrOfColumns = 0;
int nrOfElements = 0;
bool valid = false;
构造函数:
CommCREATETABLE(string command, string* columns, string* commandData, int nrOfRows, int nrOfElements) {
this->setNrOfColumns(nrOfRows);
this->setNrOfElements(nrOfElements);
this->setCommand(command);
this->setColumns(columns);
this->setCommandData(commandData);
this->valid = checkInput(this->commandData, this->columns);
this->setTableName(commandData[0]);
}
拷贝构造函数、拷贝赋值运算符、析构函数:
CommCREATETABLE(const CommCREATETABLE& comm) {
this->setNrOfColumns(comm.nrOfColumns);
this->setNrOfElements(comm.nrOfElements);
this->setCommand(comm.fullCommand);
this->setColumns(comm.columns);
this->setCommandData(comm.commandData);
this->setTableName(comm.tableName);
this->valid = comm.valid;
}
~CommCREATETABLE() {
if (this->columns != nullptr) {
delete[] this->columns;
}
if (this->commandData != nullptr) {
delete[] this->commandData;
}
}
CommCREATETABLE& operator=(const CommCREATETABLE& comm) {
this->setCommand(comm.fullCommand);
this->setColumns(comm.columns);
this->setCommandData(comm.commandData);
this->setTableName(comm.tableName);
this->setNrOfColumns(comm.nrOfColumns);
this->setNrOfElements(comm.nrOfElements);
this->valid = checkInput(this->commandData, this->columns);
return *this;
}
处理动态内存分配的唯一setter如下:
void setColumns(const string* columns) {
if (this->nrOfColumns >= 0) {
this->columns = new string[this->nrOfColumns];
memcpy(this->columns, columns, this->nrOfColumns * sizeof(string));
}
else throw EmptyCommandException();
}
void setCommandData(const string* commandData) {
if (this->nrOfElements >= 0) {
this->commandData = new string[this->nrOfElements];
memcpy(this->commandData, commandData, this->nrOfElements * sizeof(string));
}
else throw EmptyCommandException();
}
【问题讨论】:
-
0xDDDDDDDD 在 Visual Studio 中意味着您正在取消引用指向已释放堆内存的指针:https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations
-
我会避免像现在这样使用
memcpy(最后一对方法)。string类内部包含一个指针,您现在正在做的是复制该指针。这意味着当原始字符串被删除时,指针不再有效。但是,您的班级仍然拥有相同的指针。因此,当您的类被删除时,它会再次尝试删除该指针。这显然会导致问题。相反,只需使用=复制数组中的每个字符串,循环遍历所有字符串,即可解决问题。
标签: c++ constructor destructor copy-constructor memcpy