Is a default value of nullptr in a map of pointers defined behaviour?

后端 未结 2 747
别跟我提以往
别跟我提以往 2020-12-11 18:08

The following code seems to always follow the true branch.

#include 
#include 

class TestClass {
  // implementation 
}

int mai         


        
相关标签:
2条回答
  • 2020-12-11 18:38

    The map always value-initializes its members (in situations where they are not copy-initialized, of course), and value-initialization for builtin types means zero-initialization, therefore it is indeed defined behaviour. This is especially true for the value part of new keys generated when accessing elements with operator[] which didn't exist before calling that.

    Note however that an uninizialized pointer is not necessarily a null pointer; indeed, just reading its value already invokes undefined behaviour (and might case a segmentation fault on certain platforms under certain circumstances). The point is that pointers in maps are not uninitialized. So if you write for example

    void foo()
    {
      TestClass* p;
      // ...
    }
    

    p will not be initialized to nullptr.

    Note however that you might want to check for presence instead, to avoid accumulating unnecessary entries. You'd check for presence using the find member function:

    map<int, TestClass*>::iterator it = TestMap.find(203);
    if (it == map.end())
    {
      // there's no such element in the map
    }
    else
    {
      TestClass* p = it->second;
      // ...
    }
    
    0 讨论(0)
  • 2020-12-11 18:53

    Yes, that's defined behaviour. If an element isn't yet in a map when you access it via operator[], it gets default constructed.

    0 讨论(0)
提交回复
热议问题