次のコードは、常に真の分岐に従っているようです。
#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;
}
初期化されていないポインタが を指すように定義された動作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) {
if (instances[path] == nullptr) {
instances[path] = new Log(path);
}
return instances[path];
}
1 つの解決策は、これに似たものを使用して、map
. ただし、私の理解では、これによりルックアップの複雑さがO(n)
代わりにO(1)
. これは私のシナリオではそれほど大きな問題ではありません (ほんの一握りのログしかありません) が、より良い解決策は、デフォルトLog*
で参照する型のポインターを強制することで、ルックアップ チェックと移植性を同時に行うことです。時間。これは可能ですか?もしそうなら、どうすればいいですか?nullptr
O(1)