[英]My copy constructor is causing my methods which use my class to fail. Can someone take a look at it and tell me what I am doing incorrectly?
My constructor creates a copy just fine - but when a method takes an IntegerNumber as an argument, it stops working. 我的构造函数很好地创建了一个副本-但是当一个方法将IntegerNumber作为参数时,它将停止工作。
My constructor: 我的构造函数:
IntegerNumber::IntegerNumber(const IntegerNumber &integerInput){
//Creates a copy of an Integer Number
//Set len and isNegative
len = integerInput.len;
isNegative = integerInput.isNegative;
//Fill integer with IntegerInput
integer = new char[len+1];
for(int i = 0; i <= len; i++)
integer[i]=integerInput.integer[i];
}
My destructor: 我的析构函数:
IntegerNumber::~IntegerNumber(){
//Destructs IntegerNumber
delete [] integer;
delete &len;
delete &isNegative;
}
My Class' data members: 我班的数据成员:
private:
char *integer;
int len;
bool isNegative;
Please try and help me figure out what could be wrong with my constructor/destructor such that the program stops but doesnt crash or break? 请尝试帮助我弄清楚我的构造函数/析构函数可能出了什么问题,从而使程序停止但不会崩溃或中断?
you dont want this: 你不想要这样:
delete &len;
delete &isNegative;
deleting instance variables like this is undefined bahaviour so your program can stop 删除这样的实例变量是未定义的行为,因此您的程序可以停止
Use std::unique_ptr
and other classes to manage memory- always. 使用
std::unique_ptr
和其他类始终管理内存。 Dynamic arrays particularly are suited to std::vector<T>
. 动态数组特别适合于
std::vector<T>
。 Do not manually manage your memory- you will get ALL THE ERRORS. 不要手动管理您的内存,您将得到所有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.