Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way of allocating C++ class member data?

Let's say I have a class that allocates some arbitrary member data. There are two common ways that I have seen used (I know that there are others):

class A
{
    public:
        A();
        ~A();

        //Accessors...
    private:
        B *mB;
}

A::A()
{
    mB = new B();
}

A::~A()
{
    delete B;
}

Versus...

class A
{
    public:
        //Accessors...
    private:
        B mB;
}

Assume that A itself will be allocated on the heap by consumer code.

In the general case, which method is preferred? I realize that specific situations really encourage one way or the other, but in absence of those demands, is one way preferred? What are the tradeoffs?

like image 798
Rob Cooke Avatar asked Dec 12 '25 04:12

Rob Cooke


1 Answers

The second is the preferred route. Do not use new / delete unless you specifically need a variable to be on the heap or have a lifetime longer than it's container. C++ value types are easier to manage and have less error cases to worry about IMHO

like image 97
JaredPar Avatar answered Dec 14 '25 18:12

JaredPar