【问题标题】:A class with a pointer pointing to another class as a member variable and pushing it into vector具有指向另一个类的指针作为成员变量并将其推入向量的类
【发布时间】:2022-10-25 19:12:55
【问题描述】:
using namespace std;
class B {
public:
    B() :m_i(0), m_Name("") {};
    B(const int num, const string& name) :m_i(num), m_Name(name) {};
    void showInfo() {
        cout << this->m_i << ", " << this->m_Name << endl;
    }
    friend class A;
private:
    int m_i;
    string m_Name;
};

class A {
public:
    A(const int num, const string& name) :m_i(num), m_Name(name), ptr(nullptr) {};
    A(const A& orig) {
        m_i = orig.m_i;
        m_Name = orig.m_Name;
        ptr = new B;
        ptr = orig.ptr;
    }
    void showInfo() {
        cout << this->m_i << " " << this->m_Name << endl;
        if (ptr) {
            cout << ptr->m_i << " " << ptr->m_Name << endl;
        }
    }
    ~A() {
        delete ptr;
    }
    friend class C;
private:
    int m_i;
    string m_Name;
    B* ptr;
};
class C {   
public:
    void function() {
        A instanceA1(10, "Hello");
        A instanceA2(11, "Hello");
        A instanceA3(12, "Hello");
        {//another scope
            B* instanceB1 = new B(10, "Bye");
            instanceA1.ptr = instanceB1;
            B* instanceB2 = new B(11, "Bye");
            instanceA2.ptr = instanceB2;
            B* instanceB3 = new B(12, "Bye");
            instanceA3.ptr = instanceB3;
        }
        DB.push_back(instanceA1);
        DB.push_back(instanceA2);
        DB.push_back(instanceA3);

        DB[0].showInfo();
        DB[1].showInfo();
        DB[2].showInfo();
    };
private:
    vector<A> DB;
};

int main(void) {
    C console;
    console.function();
}

我必须构建一个 A 的复制构造函数,因为有一个指针作为成员变量,并且据我所知 push_back() 只对对象进行“浅拷贝”。 然而,虽然我想要的输出是 10 Hello 10 Bye 11 Hello 11 Bye 12 Hello 12 Bye 它什么也没打印。 如果我在 A 的析构函数中删除 delete ptr;,它会打印出我想要的但我很漂亮 确定有内存泄漏。 我在这里做错了什么?

【问题讨论】:

    标签: c++ heap-memory dynamic-memory-allocation stack-memory shallow-copy


    【解决方案1】:

    这是您的复制构造函数:

    A(const A& orig) {
        m_i = orig.m_i;
        m_Name = orig.m_Name;
        ptr = new B;
        ptr = orig.ptr;
    }
    

    您将 ptr 分配给一个新的 B,但随后您转身将其丢弃,使其指向原始 B。我认为这不是您想要的。这个怎么样:

        ptr = new B(*orig.ptr);
    

    这有帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多