2

gcc, clang, and msvc all reject the following code:

#include <memory>
#include <vector>

int main() {
    auto _ = std::vector<int const>{};     // error
    auto _ = std::vector<int volatile>{};  // error
    auto _ = std::vector<int&>{};          // error
}

See also https://godbolt.org/z/3GY9E66xh

This is because std::allocator<T> doesn't accept T if it is qualified by const, volatile, or reference. I just wonder:

Is it required by the C++ standard that T must not be qualified by const, volatile, or reference in std::allocator<T>?

9
  • have you read the error message you get when doing one of these? Commented Jul 11 at 9:37
  • 2
    static_assert(std::is_object_v<Key>, "The C++ Standard forbids containers of non-object types because of [container.requirements]."); Commented Jul 11 at 9:39
  • @MarcusMüller libc++ uses static_assert to ensure value_type is unqualified. I just wonder if that is also explicitly required by the C++ standard. Commented Jul 11 at 9:40
  • 1
    std::set can have const qualified types Commented Jul 11 at 10:00
  • 1
    en.cppreference.com/w/cpp/named_req/Allocator.html -- I think that should answer it. Commented Jul 11 at 10:04

1 Answer 1

8

Excerpts from the lastest C++ standard n5008 (emphasis mine):

Section 16.4.4.6.1/p2 [allocator.requirements.general]

  • T, U, C denote any cv-unqualified object type,
  • X denotes an allocator class for type T,

Section 6.8.1/p8 [allocator.requirements.general]

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not cv void.

For std::allocator<T>, T must be cv-unqualified object type, and an object type must not be a reference type. So we can say:

The C++ standard explicitly requires the template parameter type T in std::allocator<T> must not be qualified by const, volatile, or reference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.