我创建了一个类类型 Test 和带有参数的构造函数,但是,当我想通过函数 f 将我创建的构造函数分配给一个新的构造函数时,程序崩溃了!有人知道为什么吗!?
代码:
class Test
{
public:
int number;
int *a;
Test(int n){
a = new int[n];
}
~Test(){
delete []a;
}
};
Test f(Test Ft1)
{
// Do something.
return Ft1;
}
int main()
{
Test t1(3);
t1.number = 5;
Test t2 = f(t1);
return 0;
}
最佳答案
问题是您要删除同一个数组两次 a
什么时候t1
和 t2
析构函数被称为:
t1
和 t2
有他们的成员变量 a
指向相同的内存位置。当你做 Test t2 = f(t1)
, t1
的拷贝已创建并分配给 t2
.您没有定义特定的复制构造函数,因此编译器为您隐式定义了它。然而,它只是简单地复制了 a
的值。 (并且不会像您预期的那样进行 new
分配)。
作为最佳实践,我建议添加您自己的:
- 复制构造函数
- 复制作业
(参见 rule of three
)
关于变量成员a
设计:
- 如果你想要 t1
和 t2
指向同一个数组,那么你可以使用shared_ptr
- 如果你想要 t1
和 t2
拥有自己的数组,那么使用 vector<int>
会更简单对于 a
编辑:如果您需要使用原始指针,这里有一个快速示例,说明如何在复制构造函数和运算符赋值中管理内存。我可以推荐你阅读一本关于它的引用书(例如 Effective C++ , chapter 11
)吗?它将向您解释关键概念和陷阱。
class Test{
public:
int number;
int *a;
Test(int n){
a = new int[n];
}
~Test(){
delete [] a;
}
Test(const Test& that)
{
int size = sizeof(that.a);
a = new int[size];
memcpy (a, that.a, sizeof(size));
}
Test& operator=(const Test& that)
{
if (this != &that)
{
delete [] a;
int size = sizeof(that.a);
a = new int[size];
memcpy (a, that.a, sizeof(size));
}
return *this;
}
};
Test f(Test Ft1){
//do something
return Ft1;
}
int main(){
Test t1(3);
t1.number = 5;
Test t2 = f(t1);
// Test t3(t1); // calls copy constructor
// t3 = t1; // calls assignment operator
return 0;
}
关于c++ - 在 C++ 中将类构造函数分配给带有参数的新构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19603764/