Question about storing array in a std::vector in C++

前端 未结 7 1335
灰色年华
灰色年华 2021-01-12 17:07

I am unclear about the following.

First, this code compiles fine:

#include 

typedef struct{
    int x1,x2,x3,x4;
}  ints;

typedef std         


        
7条回答
  •  独厮守ぢ
    2021-01-12 17:29

    The requirement for value type T for all STL containers, including std::vector, is that T is Assignable - ISO C++03 23.1[lib.container.requirements]/4-5. Assignable is defined as follows:

    Expression t = u, where t is of type T, and u is of type cv T, is valid, its return type is T&, and the post-condition is that t is equivalent to u.

    Arrays do not fulfill this requirement, because you cannot write:

    int a[2], b[2];
    a = b;
    

    The reason why you cannot is because both a and b in the code snippet above decay to pointer-type rvalues according to the usual C++ rules for array-to-pointer decay described in 4.2[conv.array]. Naturally, an rvalue if not permitted on the left side of non-overloaded operator=.

提交回复
热议问题