以下代码似乎始终遵循true分支.
#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;
}
Run Code Online (Sandbox Code Playgroud)
它是否为未初始化的指针定义了行为nullptr
,或者是我的编译器的工件?
如果没有,我如何确保以下代码的可移植性?目前,我正在使用类似的逻辑来返回正确的单例实例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) …
Run Code Online (Sandbox Code Playgroud)