【发布时间】:2014-03-06 18:00:54
【问题描述】:
所以我有以下std::map:
std::map<int, float*> map;
使用其operator []访问此地图:
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();
p 和p1 确实为空,不用担心。
【问题讨论】:
-
为什么不直接测试呢?
-
应该是
it != map.end() -
或者Read The Fine Manual具体的?
-
@JoachimPileborg 我们正在开发一些多平台库,我们不可能在所有编译器上测试它。即使只在主要编译器上进行测试也需要一些时间。