简体   繁体   中英

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM