简体   繁体   中英

Should I call clear before use std::map in cpp

I want to know if I must clear std::map before using it? For example, in the following code should I call m_map.clear in the constructor?

struct stu
{
  ...
}

class A
{
 public:
     A()
       {
          m_map.clear;  // is this necessary?
       };
     ~A();

 private:
     map<int ,stu> m_map;
}

There is no need to call clear() in the constructor of your class.

A good way to know exactly what a particular method from the STL does, and hence when and why you should call it, is by searching a good reference website such as: http://en.cppreference.com/w/cpp/container/map

If you navigate down the page, you will find the clear method, and after following the link, a description of its functionality "Removes all elements from the container." Have you added any elements to this container yet? No, so there is no need to call this method.

Furthermore: How do you know what state any data member is in if you don't perform any initialization operation on it? In this case there is a guarantee that the default constructor of a member variable, the std::map m_map variable, is called. The default constructor of a class is the constructor method which takes no parameters, or where all the parameters are supplied via default values. Once again the supplied reference website states for the default constructor "1) Default constructor. Constructs empty container." So your container (and many of the other STL containers), is perfectly ready to be used right away, without clearing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM