Search code examples
c++pointersmembersetterownership

setting a pointer member variable correctly


I have a class L simplified as follows :

class L
{
    private:
        C * _pc ;
    public:
        C * getc() const ; // getter
        void setc(const C * ipc); //setter
        ~L()
        {
            delete _pc ;
        }
};

where C is another class.

I also have a helper class CHelper simplified as follows :

class CHelper
{
    C _c ;
    CHelper(L & ic)
    {
        // 1st constructs _c (code omitted);
        // then sets ic's _pc pointer member variable :
        ic.setc(&_c);
    }
};

I feel that there will be a problem with the deletion of _pc somehow, without being sure. What about it ?

What are the flaws of such an approch ? How can I reach the same "functionality" (setting correctly a pointer member variable) with a correct approach ?


Solution

  • Your code currently doesn't compile. CHelper's constructor asks for a C object. The C class (probably) doesn't have the setc method. you probably meant CHelper(L& ic).

    Anyway, If your CHelper object goes out of scope and is destroyed then the member variable _c is destroyed along with it. Leaving you with a dangling pointer in your L object. Not only that, but L currently also violates the rule of three/five.

    If you have access to C++11 I would greatly suggest to replace the raw pointer _pc and _c with a std::shared_ptr if the CHelper class is necessary ( and thus removing the delete in that destructor) and otherwise a std::unique_ptr.