Why does a class used as a value in a STL map need a default constructor in …?

僤鯓⒐⒋嵵緔 提交于 2019-12-19 02:14:10

问题


Below is the class used as the value in a map:

class Book
{
    int m_nId;
public:
    // Book() { }  <----- Why is this required?
    Book( int id ): m_nId( id ) { }

};

Inside main():

map< int, Book > mapBooks;

for( int i = 0; i &lt 10; ++i )
{
    Book b( i );
    mapBooks[ i ] = b;
}

The statement causing the error is:

mapBooks[ i ] = b;

If I add a default constructor, the error does not appear. However, I don't understand why the need. Can anyone explain? If I use insert(), the problem does not appear.

By the way, I'm using Visual C++ 2008 to compile.


回答1:


operator[] performs a two step process. First it finds or creates a map entry for the given key, then it returns a reference to the value part of the entry so that the calling code can read or write to it.

In the case where entry didn't exist before, the value half of the entry needs to be default constructed before it is assigned to. This is just the way the interface needs to work to be consistent with the case where the entry already existed.

If need to use such a type in a map then you have to avoid the use of operator[] by using find and insert "manually".



来源:https://stackoverflow.com/questions/2346797/why-does-a-class-used-as-a-value-in-a-stl-map-need-a-default-constructor-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!