Let's say a class has been defined as
class A {
//.....
};
and now I am creating two objects as
A a,b;
In what order are a
and b
created? Is it defined by the standard?
Let's say a class has been defined as
class A {
//.....
};
and now I am creating two objects as
A a,b;
In what order are a
and b
created? Is it defined by the standard?
From 8 Declarators [dcl.decl] 3:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
It goes on to say
A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is
T D1, D2, ... Dn;
is usually equivalent toT D1; T D2; ... T Dn;
whereT
is a decl-specifier-seq and eachDi
is an init-declarator. An exception occurs when a name introduced by one of the declarators hides a type name used by the decl-specifiers, so that when the same decl-specifiers are used in a subsequent declaration, they do not have the same meaning.
You can say that they are constructed from left to right.
T D1,D2=D1;
becomes T D1; T D2=D1;
by the rules so yes. –
Roop D1
and copy assignment on D2
with D1
. –
Socialization D2
. Not the copy assignment operator. –
Evetta S S,T;
works; S S; S T;
is an error. Newer example is auto x=1; auto y=2.0;
works; auto x=1,y=2.0;
is an error. Those are the only examples the footnote provides. So "usually" is, if anything, a bit of an understatement. –
Deweese S S, T;
–
Socialization C++ spec chapter 8 [dcl.decl], says:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself. (100)
Footnote (100) goes on to say:
(100) A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is
T D1, D2, ... Dn;
is usually equivalent to
T D1; T D2; ... T Dn;
...and then names some exceptions, none of which apply in such simple cases.
So the answer to your question is that the objects are constructed in the order you list them. And no, it is not a comma operator.
The order is the written order, from left to right. Also, it's not the comma operator, but simply a list of declarators. When a user-defined comma operator is used, order is in fact unspecified.
See comma operator and declarators.
a will be created first and then b.
Commas in this case will be used as separators and not as operators.
For example from wikipedia :
/**
* Commas act as separators in this line, not as an operator.
* Results: a=1, b=2, c=3, i=0
*/
int a=1, b=2, c=3, i=0;
Standards:
Declarators [dcl.decl]:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
Example:
class A {
public:
A(std::string const &s): name(s)
{
std::cout << "I am " << name << '\n';
}
std::string name;
};
auto main() -> int
{
A a("a"), b("b");
}
Output:
I am a
I am b
© 2022 - 2024 — McMap. All rights reserved.