leon22
leon22

Reputation: 5649

Correct use of std::map as class member

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!

Upvotes: 6

Views: 6445

Answers (2)

ChronoTrigger
ChronoTrigger

Reputation: 8607

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.

Upvotes: 4

zennehoy
zennehoy

Reputation: 6846

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

Upvotes: 9

Related Questions