Take the 2-minute tour ×

In the past I always created a map like this:

class TestClass
        std::map<int,int> *mapA;

    mapA = new std::map<int,int>();

    mapA->clear(); // not necessary
    delete mapA;

So, now I read all over the place at Stackoverflow: avoid pointers as often as possible

Currently I want to create the map without pointer and new (no need to delete the object by myself and less danger of getting some memory leak)!

class TestClass
        TestClass() : mapA() // this is also needed?
        std::map<int,int> mapA;

Any further steps for correct creation of the map necessary?

Thanks for any help and/or clarification!

share|improve this question
I just noticed you edited in a mapA->clear() to your original destructor. This is not necessary - the map will clear itself during deconstruction. –  zennehoy Sep 27 '13 at 8:20
You dont need to call map::clear in either case. –  Ajay Sep 27 '13 at 8:21

2 Answers 2

up vote 6 down vote accepted

Nope that's it, and you don't need to explicitly initialize it in the constructor.

share|improve this answer
I'm always surpised that although the pointerless code is much simpler than the pointer code, newbies always seem to go for the pointer version. –  john Sep 27 '13 at 8:37
@john Maybe this is not so; it is only that those who go for the pointer get in trouble and we notice them. –  Gorpik Sep 27 '13 at 8:44
@john Frequently people come over from Java, and since you have to new everything over in Java, they do the same in C++. –  Andre Kostur Sep 27 '13 at 14:23

As zennehoy says, it is not necessary to initialize the map in the TestClass constructor. Let me note a difference between the two implementations:

In the first one, the TestClass, as it is currently written, is not copyable without undesirable effects because the raw pointer to the dynamically allocated map is copied:

TestClass *A = new TestClass;      // A has a map
TestClass *B = new TestClass(A);   // B shares the map with A!

delete A; // this deletes A's map (in destructor)
delete B; // this deletes A's map again! wrong

In your second implementation, that does not happen because the map, and not just its address, is copied completely.

To solve that issue in your first implementation, you should use a shared pointer, or do the work yourself by implementing the operator= and the copy constructor. Or, if you want to really share the map between copied instances, you should implement a reference counting mechanism.

share|improve this answer

Your Answer


