You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何覆写变量时析构函数会删除新类数据?如何实现可变长数组类?

解决方案1:用std::vector(最推荐,新手友好)

直接用C++标准库的std::vector代替手动管理的动态数组,它会自动处理内存分配、释放、拷贝和赋值,完全不用你操心。修改后的代码如下:

#include <iostream>
#include <vector> // 引入vector头文件

using namespace std;

class foo
{
private:
    vector<int> bar; // 替换成vector
public:
    foo(int length);
    // 不需要手动写析构函数了,vector会自动处理
    void print_bar() {
        cout << "bar = {"; 
        for (int num : bar) {cout << num << ", ";} 
        cout << "}" << endl;
    }
};

foo::foo(int length) : bar(length, 0) { // 初始化vector为length个0
    cout << "Creating with length " << length << endl;
    cout << "Created with bar = {"; 
    for (int num : bar) {cout << num << ", ";} 
    cout << "}" << endl;
}

int main() {
    foo a = foo(1);
    a = foo(2);
    a.print_bar();
    return 0;
}

运行这段代码,输出会完全符合你的预期,而且没有任何内存问题。


解决方案2:手动实现赋值运算符和拷贝构造函数(进阶)

如果一定要自己管理动态数组,必须遵守C++的三法则:如果类有自定义的析构函数,就必须手动实现拷贝构造函数和赋值运算符重载,避免浅拷贝问题。修改后的代码如下:

#include <iostream>

using namespace std;

class foo
{
private:
    int *bar;
    int l;
public:
    foo(int length);
    foo(const foo& other); // 拷贝构造函数
    foo& operator=(const foo& other); // 赋值运算符重载
    ~foo();
    void print_bar() {
        cout << "bar = {"; for (int i = 0; i < l; i++) {cout << bar[i] << ", ";} cout << "}" << endl;
    }
};

foo::foo(int length) {
    this->l = length;
    cout << "Creating with length " << l << endl;
    bar = new int[l];
    for(size_t i = 0; i < l; ++i) {bar[i] = 0;}
    cout << "Created with bar = {"; for (int i = 0; i < l; i++) {cout << bar[i] << ", ";} cout << "}" << endl;
}

// 拷贝构造函数:深拷贝
foo::foo(const foo& other) {
    this->l = other.l;
    bar = new int[l];
    for(size_t i = 0; i < l; ++i) {bar[i] = other.bar[i];}
}

// 赋值运算符重载:先释放自己的内存,再深拷贝
foo& foo::operator=(const foo& other) {
    if (this == &other) return *this; // 防止自赋值
    // 释放当前对象的旧内存
    delete[] bar;
    // 分配新内存并复制数据
    this->l = other.l;
    bar = new int[l];
    for(size_t i = 0; i < l; ++i) {bar[i] = other.bar[i];}
    return *this;
}

foo::~foo() {
    cout << "Deleted with bar = {"; for (int i = 0; i < l; i++) {cout << bar[i] << ", ";} cout << "}" << endl;
    delete[] bar;
}

int main() {
    foo a = foo(1);
    a = foo(2);
    a.print_bar();
    return 0;
}

这段代码通过深拷贝(复制指针指向的内容,而不是指针本身)解决了浅拷贝的问题,运行后输出也会符合你的预期。


内容的提问来源于stack exchange,提问作者Vitphire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:31:03