0

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 ?

2
  • The second one could get you in all sorts of trouble, if you don't properly implement the rule of 3 or 5. Commented Mar 10, 2021 at 16:49
  • 1
    The rule of thumb is to never use new and delete, and use containers and smart pointers instead. The only exception is when you're writing a custom container or smart pointer. Commented Mar 10, 2021 at 17:56

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

1 Comment

Even in that case, if anything, you should use std::unique_ptr instead of manually allocating the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.