Vector of structs with const members?

后端 未结 4 1244
有刺的猬
有刺的猬 2021-01-11 16:07

Let\'s say I have

#include 
#include 
using namespace std;

struct Student
{
    const string name;
    int grade;
    Student(co         


        
4条回答
  •  情深已故
    2021-01-11 17:02

    You can't. Your type violates the "Assignable" requirement for standard containers.

    ISO/IEC 14882:2003 23.1 [lib.container.requirements] / 3:

    The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

    From table 64 (Assignable requirements):

    In Table 64, T is the type used to instantiate the container, t is a value of T, and u is a value of (possibly const) T.

    expression: t = u; return type: T; post-condition: t is equivalent to u

    In theory, a std::vector equivalent could choose to do destruction and copy construction in all cases, but that's not the contract that has been chosen. If reallocation isn't required, then using the contained type's assignment operator for things like vector::operator= and vector::assign might be significantly more efficient.

提交回复
热议问题