Jolly Roger
Jolly Roger

Reputation: 1134

std::map as class member

I have a class X with a member std::map<int,int> m_lookupTable. Which of the following should I use :

Class X {
...
private:
    std::map<int,int> m_lookupTable;
...
}

or allocate using new and delete in destructor of Class

class X{
private:
   std::map<int,int>* m_lookupTable;
    X() {
        m_lookupTable = new std::map<int,int>();
    }
    
   ~X(){
       delete m_lookupTable;
    }
} 

What should be preferred way and why ?

Upvotes: 0

Views: 77

Answers (3)

Bill
Bill

Reputation: 21

As has already been stated above, the use of an automatic is almost always preferred. It is far simpler, and will have far fewer maintenance issues in the long term.

Having said that, there is a case for using a pointer IF you are storing a large number of objects of type X, only SOME of them need the m_lookupTable, AND you are in a memory constrained environment. This is a rare combination, but not impossible.

Upvotes: 1

Devolus
Devolus

Reputation: 22094

I would recommend to use a simple member. Dynamically allocating it, has no benefit, and adds unneccasry overhead for no reason. It also potentially introduces memory leaks if wrongly handled.

You also have to take care when you use assignment or copying of your class, which you have to handle yourself then.

Always prefer automatic over dynamic objects if possible.

Upvotes: 8

Mark Ransom
Mark Ransom

Reputation: 308528

When the lifetime of the member object will be the same as the lifetime of the outer object, there's almost no reason to prefer a pointer. It just leads to more complex code and more chance for bugs or memory leaks. This is doubly true when it's a private member, because it's unlikely in that case that the object lifetimes will need to be different.

Upvotes: 2

Related Questions