Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c++ - Does C++11 allow vector<const T>?

Container requirements have changed from C++03 to C++11. While C++03 had blanket requirements (e.g. copy constructibility and assignability for vector), C++11 defines fine-grained requirements on each container operation (section 23.2).

As a result, you can e.g. store a type that is copy-constructible but not assignable - such as a structure with a const member - in a vector as long as you only perform certain operations that do not require assignment (construction and push_back are such operations; insert is not).

What I'm wondering is: does this mean the standard now allows vector<const T>? I don't see any reason it shouldn't - const T, just like a structure with a const member, is a type that is copy constructible but not assignable - but I may have missed something.

(Part of what makes me think I may have missed something, is that gcc trunk crashes and burns if you try to instantiate vector<const T>, but it's fine with vector<T> where T has a const member).

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, I believe the allocator requirements say that T can be a "non-const, non-reference object type".

You wouldn't be able to do much with a vector of constant objects. And a const vector<T> would be almost the same anyway.


Many years later this quick-and-dirty answer still seems to be attracting comments and votes. Not always up. :-)

So to add some proper references:

For the C++03 standard, which I have on paper, Table 31 in section [lib.allocator.requirements] says:

T, U any type

Not that any type actually worked.

So, the next standard, C++11, says in a close draft in [allocator.requirements] and now Table 27:

T, U, C any non-const, non-reference object type

which is extremely close to what I originally wrote above from memory. This is also what the question was about.

However, in C++14 (draft N4296) Table 27 now says:

T, U, C any non-const object type

Possibly because a reference perhaps isn't an object type after all?

And now in C++17 (draft N4659) it is Table 30 that says:

T, U, C any cv-unqualified object type (6.9)

So not only is const ruled out, but also volatile. Probably old news anyway, and just a clarification.


Please also see Howard Hinnant's first-hand info, currently right below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...