【问题标题】:Default value of a pointer in a new std::map entry新 std::map 条目中指针的默认值
【发布时间】: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();

pp1 确实为空,不用担心。

【问题讨论】:

  • 为什么不直接测试呢?
  • 应该是it != map.end()
  • 或者Read The Fine Manual具体的?
  • @JoachimPileborg 我们正在开发一些多平台库,我们不可能在所有编译器上测试它。即使只在主要编译器上进行测试也需要一些时间。

标签: c++ pointers stl


【解决方案1】:

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

【讨论】:

  • 伙计,这些天我真的应该阅读标准。这很棒。
猜你喜欢
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 2016-02-22
  • 1970-01-01
  • 2013-01-05
  • 2012-04-27
  • 2019-04-01
相关资源
最近更新 更多