user10000100_u user10000100_u - 1 month ago 5x
C++ Question

setting a pointer member variable correctly

I have a class

simplified as follows :

class L
C * _pc ;
C * getc() const ; // getter
void setc(const C * ipc); //setter
delete _pc ;

is another class.

I also have a helper class
simplified as follows :

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

I feel that there will be a problem with the deletion of
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 ?


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.