c++ - 新 std::map 条目中指针的默认值

标签 c++ pointers stl

所以我有以下 std::map:

std::map<int, float*> map;

使用它的 operator [] 访问此 map :

float *pointer = map[123];

现在如果映射中不存在键 123,则指针的值将是未定义的。那是对的吗?要确保它是:

template <class T>
struct PtrWithDefault {
    T *p;
    PtrWithDefault() :p(0) {} // default
    PtrWithDefault(T *ptr) :p(ptr) {}
    PtrWithDefault(PtrWithDefault other) :p(other.p) {} // copy
    operator T *() { return p; }
};
std::map<int, PtrWithDefault<float> > map;

现在做同样的事情可以确保指针的正确初始化。还有其他办法吗?这是一种丑陋的解决方案。我的最终目标是速度:

std::map<int, float*> map;
float *p;
std::map<int, float*>::iterator it = map.find(123);
if(it != map.end())
    p = (*it).second; // just get it
else
    map[123] = p = 0;

这会比使用默认指针的解决方案更快吗?有没有更好的方法来做到这一点?

编辑

好吧,这对我来说完全是愚蠢的。正如 Brian Bi 正确所说的那样,由于零初始化,指针将自动初始化。自 C++03 以来就存在值初始化,而 C++98(这是 Visual Studio 2008 中唯一可用的标准)没有。

无论如何,它很容易验证为:

std::map<int, float*> map;
typedef float *P;
float *p = map[123], *p1 = P();

pp1 确实是null,不用担心。

最佳答案

如果在映射中未找到键,则插入的值将被值初始化 (§23.4.4.3/1)。所以不需要包装器;插入的指针将是空指针。

关于c++ - 新 std::map 条目中指针的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232385/

相关文章:

c - malloc 中的 Sigsegv

c++ - STL 容器的抽象包装器?

c++ - C 的标准库

c++ - gcc 无法编译命名空间中的静态函数

c - C 中的指针寻址

c++ - 如何对齐结构数组,每个都需要对齐(SSE)

c - 如何在c中正确分配和打印结构指针?

STL - 我可以在 DriverKit 驱动程序中使用 STL 吗?

c++ - Blade 的扭曲效果 (glRotatef) 不起作用

c++ - DirectX:在设备之前获取InfoQueue