Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of std::map as class member

Tags:

c++

pointers

map

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!

like image 770
leon22 Avatar asked Dec 20 '22 23:12

leon22


1 Answers

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

like image 160
zennehoy Avatar answered Dec 22 '22 14:12

zennehoy