6

In the past I always created a map like this:

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

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

TestClass::~TestClass
{
    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
{
    public:
        TestClass() : mapA() // this is also needed?
        {};
    private:
        std::map<int,int> mapA;
};

Any further steps for correct creation of the map necessary?

Thanks for any help and/or clarification!

2
  • 1
    I just noticed you edited in a mapA->clear() to your original destructor. This is not necessary - the map will clear itself during deconstruction. Commented Sep 27, 2013 at 8:20
  • You dont need to call map::clear in either case. Commented Sep 27, 2013 at 8:21

2 Answers 2

9

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

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

6 Comments

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 Maybe this is not so; it is only that those who go for the pointer get in trouble and we notice them.
@john Frequently people come over from Java, and since you have to new everything over in Java, they do the same in C++.
Andre, john: and from C, or course, the original home hell of pointers. @Gorpik: :-))
Why don't we need to initialize the map in the member initializer list ?
|
4

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.

Comments

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.