Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - What is assignment via curly braces called? and can it be controlled?

What is this called?

Vec3 foo = {1,2,3};

Can it be controlled via an operator or some such? As in can I specify how this should act?

For instance if I had some complicated class could I use this to assign variables? (Just an exercise in curiosity).

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

That is not assignment. That is initialization.

Such initialization is allowed for aggregate only, that includes POD class. POD means Plain Old Data type.

Example,

//this struct is an aggregate (POD class)
struct point3D
{
   int x;
   int y;
   int z;
};

//since point3D is an aggregate, so we can initialize it as
point3D p = {1,2,3};

See the above compiles fine : http://ideone.com/IXcSA

But again consider this:

//this struct is NOT an aggregate (non-POD class)
struct vector3D
{
   int x;
   int y;
   int z;
   vector3D(int, int, int){} //user-defined constructor!
};

//since vector3D is NOT an aggregate, so we CANNOT initialize it as
vector3D p = {1,2,3}; //error

The above does NOT compile. It gives this error:

prog.cpp:15: error: braces around initializer for non-aggregate type ‘vector3D’

See yourself : http://ideone.com/zO58c

What is the difference between point3D and vector3D? Just the vector3D has user-defined constructor, and that makes it non-POD. Hence it cannot be initialized using curly braces!


What is an aggregate?

The Standard says in section §8.5.1/1,

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

And then it says in §8.5.1/2 that,

When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.

[Example:

struct A 
{
   int x;
   struct B 
   {
      int i;
      int j;
   } b;
} a = { 1, { 2, 3 } };

initializes a.x with 1, a.b.i with 2, a.b.j with 3. ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...