使用指针复制构造函数

Big*_*iga 15 c++ pointers copy-constructor

我最近发现,当我在一个类中有指针时,我需要指定一个Copy构造函数.

为了解这一点,我做了以下简单的代码.它编译,但在执行复制构造函数时给出了运行时错误.

我试图只复制复制对象的指针中的值,但避免分配相同的地址.

那么,这里有什么问题?

    class TRY{
        public:
        TRY();
    ~TRY();
        TRY(TRY const &);

        int *pointer;

        void setPointer(int);
    };


    void TRY::setPointer(int a){
        *pointer = a;

        return;
    }


    TRY::TRY(){}


    TRY::~TRY(){}


    TRY::TRY(TRY const & copyTRY){
        int a = *copyTRY.pointer;
        *pointer = a;
    }



    int main(){

        TRY a;
        a.setPointer(5);

        TRY b = a;

        b.setPointer(8);

        cout << "Address of object a = " << &a << endl;
        cout << "Address of object b = " << &b << endl;

        cout << "Address of a.pointer = " << a.pointer << endl;
        cout << "Address of b.pointer = " << b.pointer << endl;

        cout << "Value in a.pointer = " << *a.pointer << endl;
        cout << "Value in b.pointer = " << *b.pointer << endl;

        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我将把这个概念用于其他有很多指针的类,我需要将所有值从on对象复制到另一个.最初需要复制此代码,因此我希望保持复制的可能性(我不会将复制构造函数隐藏为私有).

此外,我需要实现的真正的类有10个指针,它可能随着时间而变化.在C++中使用深度复制构造函数是否有一种更智能的方法?...

Nav*_*een 18

使用该语句,int* pointer您刚刚定义了一个指针,但尚未分配任何内存.首先,你应该通过分配一些内存来指向一个合适的内存位置:int* pointer = new int.然后再次在复制构造函数中,您必须为复制的对象分配内存.另外,不要忘记在析构函数中使用delete释放内存.

我希望这个例子有帮助:

class B
{

public:
    B();
    B(const B& b);
    ~B();
    void setVal(int val);

private:
    int* m_p;
};

B::B() 
{
    //Allocate the memory to hold an int
    m_p = new int;

    *m_p = 0;
}

B::B(const B& b)
{
    //Allocate the memory first
    m_p = new int;

    //Then copy the value from the passed object
    *m_p = *b.m_p;
}

B::~B()
{

    //Release the memory allocated
    delete m_p;
    m_p = NULL;
}

void B::setVal(int val)
{
    *m_p = val;
}
Run Code Online (Sandbox Code Playgroud)

  • 在为其分配新对象之前,不要忘记删除m_p. (3认同)
  • 在构造函数中,m_p最初将是未定义的,除非您明确地将其放入初始化列表中.如果您尝试删除未定义的指针,则会发生错误. (3认同)

aJ.*_*aJ. 9

我最近发现,当我在一个类中有指针时,我需要指定一个Copy构造函数.

这不完全正确.当你的类中有指针并使用它来分配内存时,new你必须担心复制构造函数.另外,不要忘记赋值运算符和析构函数.您必须删除使用分配的内存delete.

它被称为三巨头的法则.

例:

  ~Matrix();  //Destructor
  Matrix(const Matrix& m); //Copy constructor
  Matrix& operator= (const Matrix& m); //Assignment operator
Run Code Online (Sandbox Code Playgroud)