Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct behaviour for std::vector<T>::value_type

After scratching my head at some errors in some template code that used std::vector::value_type I tracked it down to the following. Is this correct behavior according to the standard, or is this a problem with 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");

The above assertion fails.

like image 359
Brandon Avatar asked May 02 '13 05:05

Brandon


People also ask

What is an std::vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

Should I use std for vector?

Here is a rule of thumb: If you want to add elements to your container or remove elements from your container, use a std::vector; if not, use a std::array. If you are busy, you can stop to read, if not, continue.

Does vector clear deallocate memory?

The vector's memory is not guaranteed to be cleared. You cannot safely access the elements after a clear. To make sure the memory is deallocated Scott Meyers advised to do this: Removes all elements from the vector, calling their respective destructors, leaving the container with a size of 0.

How do I print the contents of a vector file?

In the for loop, size of vector is calculated for the maximum number of iterations of loop and using at(), the elements are printed. for(int i=0; i < a. size(); i++) std::cout << a.at(i) << ' '; In the main() function, the elements of vector are passed to print them.


1 Answers

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.

like image 184
ComicSansMS Avatar answered Sep 29 '22 22:09

ComicSansMS