5

在对一些使用的模板代码中的一些错误挠头后,std::vector::value_type我将其追踪到以下内容。根据标准,这是正确的行为,还是 MSVC 2012 CTP 的问题?

typedef std::vector<int>::value_type       t1;
typedef std::vector<int const>::value_type t2;

static_assert(!std::is_same<t1, t2>::value, "hmmm");

上述断言失败。

4

3 回答 3

9

The value_type of a std::vector<T> is T (§23.3.6.1).

The value of is_same takes cv qualifiers into account (§20.9.6).

In your case that means checking std::is_same<int, int const>, which is supposed to fail.

Which in turn means that the behavior you observed is wrong according to the standard. It seems that MSVC is dropping the cv qualifiers for value_type:

std::vector<const int>::value_type val = 5;
val = 10;

This compiles on MSVC2008 but fails with gcc 4.4.

You should probably file a bug report with Microsoft.

Edit: Nawaz's comment above got me thinking. According to this question const int is indeed not allowed as a a value_type in C++03! It seems though that it is in C++11.. While it's not explicitly forbidden in C++11 for vectors, it is forbidden for allocators (§17.6.3.5), which in turn makes it illegal for vectors as well.

In any case, MSVC's behavior of silently dropping the const seems wrong here.

于 2013-05-02T08:08:33.687 回答
3

例如,GCC 4.7.2 甚至在 OP 代码到达static_assert.

问题是标准容器(例如std::vector)不是为容纳而设计的,const T因为它们依赖于分配器,并且 [allocator.requirements] 中的标准仅定义了非常量、非引用对象类型的分配器行为。

据我了解,这意味着使用会std::vector<const int>产生未定义的行为。因此,两个编译器都是对的!

另请参阅this question、this answer和Howard Hinnant对此的评论,我引用了第一句话:

底线:我们没有设计容器来容纳const T.

于 2013-05-02T08:33:11.433 回答
1

在我看来std::vector<const int>是不允许的:根据标准 T 应该是CopyInsertableconst int不是。

请参阅N3485草案中 23.2.3 序列容器 [sequence.reqmts] 中的序列容器要求

OP 代码无法在该行同时使用 gcc 4.7 和 icc 13.0 进行编译

typedef std::vector<int const>::value_type t2;

显然,MSVC 丢弃了 const 限定符。

于 2013-05-02T08:24:24.570 回答