0

As this answer said:

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector is not allowed.

class test {
public:
  test(test &) = delete;
  test &operator=(test &) = delete;
};

int main() {
  std::vector<test> vec;
}

class test is not assignable but this could compile.

Other answer like std::vector<T, std::allocator>'s allocator limitation, why those two static_assert was wrote in vector but not allocator ? Is this the real reason that limited the component type?

  template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
    class vector : protected _Vector_base<_Tp, _Alloc>
    {
#if __cplusplus >= 201103L
      static_assert(is_same<typename remove_cv<_Tp>::type, _Tp>::value,
      "std::vector must have a non-const, non-volatile value_type");
# ifdef __STRICT_ANSI__
      static_assert(is_same<typename _Alloc::value_type, _Tp>::value,
      "std::vector must have the same value_type as its allocator");
# endif
#endif

Why volatile is so special that cannot use as vector's component qualifier?

Just expecting to know why, not the solution to bypass this.

  • 1
    *"As [this answer](https://www.stackoverflow.com/) said"* -- your link is off. It goes to the main page, not an answer. – JaMiT Jan 11 '23 at 03:54
  • The `volatile` bit is an interesting question that I can make guesses at, but I'd like to see an authoritive answer . Not only are references not assignable, they are not objects. They are another name for an object. – user4581301 Jan 11 '23 at 04:14
  • `vector`'s do a lot of assigning as they shuffle their contents around during inserts and removals and you can't assign a constant value, so that one's petty simple to reason out. – user4581301 Jan 11 '23 at 04:18
  • 1
    `volatile` is not allowed because neither of vector members has volatile specifiers. – 273K Jan 11 '23 at 04:23

0 Answers0