Proper use of std :: map as a member of a class

In the past, I always created this map:

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 throughout Stackoverflow: avoid pointers as often as possible

Currently I want to create a map without a pointer and a new one (there is no need to delete the object yourself and there is less risk of a memory leak)!

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

Are further steps required to properly create a map?

Thanks for any help and / or clarification!

+4
source share
2 answers

No, this is for you, and you do not need to explicitly initialize it in the constructor.

+6
source

zennehoy, TestClass. :

TestClass, , , :

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

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

, , , .

, , operator= . , , .

+3

All Articles