Is the default value nullptr in the map specified by the behavior pointer?

The following code always seems to follow the true branch.

#include <map>
#include <iostream>

class TestClass {
  // implementation 
}

int main() {
  std::map<int, TestClass*> TestMap;
  if (TestMap[203] == nullptr) {
    std::cout << "true";
  } else {
    std::cout << "false";
  }
  return 0;
}

Is there defined behavior for an uninitialized pointer to a point nullptror artifact of my compiler?

If not, how can I ensure portability of the following code? I am currently using similar logic to return the correct singleton instance for log file:

#include <string>
#include <map>    

class Log {
  public:
    static Log* get_instance(std::string path);
  protected:
    Log(std::string path) : path(path), log(path) {};
    std::string path;
    std::ostream log;
  private:
    static std::map<std::string, Log*> instances;
};

std::map<std::string, Log*> Log::instances = std::map<std::string, Log*>();

Log* Log::get_instance(std::string path) {
  if (instances[path] == nullptr) {
    instances[path] = new Log(path);
  }
  return instances[path];
}

- , , map. , , O(n) O(1). ( ), - Log* nullptr , O(1) . , , ?

+5
2

( , , ), , . , operator[], .

, , ; , undefined ( ). , . , ,

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

p nullptr.

, , . find:

map<int, TestClass*>::iterator it = TestMap.find(203);
if (it == map.end())
{
  // there no such element in the map
}
else
{
  TestClass* p = it->second;
  // ...
}
+8

, . operator[], .

+1

All Articles