If two objects are declared in a single line, in which order are they constructed?
Solution 1:
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.
Solution 2:
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.
Solution 3:
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.
Solution 4:
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;
Solution 5:
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