c++ - 在 C++ 中将类构造函数分配给带有参数的新构造函数

标签 c++ function class constructor dynamic-arrays

我创建了一个类类型 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什么时候t1t2析构函数被称为: t1t2有他们的成员变量 a指向相同的内存位置。当你做 Test t2 = f(t1) , t1 的拷贝已创建并分配给 t2 .您没有定义特定的复制构造函数,因此编译器为您隐式定义了它。然而,它只是简单地复制了 a 的值。 (并且不会像您预期的那样进行 new 分配)。

作为最佳实践,我建议添加您自己的:
- 复制构造函数
- 复制作业
(参见 rule of three)

关于变量成员a设计:
- 如果你想要 t1t2指向同一个数组,那么你可以使用shared_ptr
- 如果你想要 t1t2拥有自己的数组,那么使用 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/

相关文章:

c++ - 如何应对 int 溢出

c++ - 模板 :Name resolution -->can any one tell some more examples for this statement?

R 调试器不会在断点处停止

c++ - 我如何在没有 Stod() 的情况下重写

php - 在一个类中混合静态和非静态方法是否可以接受?

ios - 使用 [id class] 作为指针

c++ - &arr[size] 有效吗?

适合初学者的python函数

class - 条件类导入/加载

c++ - 声明具有所有虚函数的类的对象