Copy constructor with pointers

前端 未结 9 1133
清歌不尽
清歌不尽 2020-12-14 10:08

I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor.

To learn that, I have made the following simple code. It c

9条回答
  •  被撕碎了的回忆
    2020-12-14 10:33

    With the statement int* pointer you have just defined a pointer but has not allocated any memory. First you should make it point to a proper memory location by allocating some memory like this: int* pointer = new int. Then in the copy constructor again you have to allocate the memory for the copied object. Also, don't forget to release the memory using delete in the destructor.

    I hope this example helps:

    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;
    }
    

提交回复
热议问题