In article <01fe3f54-7898-485e-8f09-706a2f351b47
@[EMAIL PROTECTED]
>, Sardaukary@[EMAIL PROTECTED]
says...
> I've just discovered that this is legal in c++.
>
> int x={10};
>
> What's the point of allowing this? Is it just to be consistent with
> the initialisation of structs and arrays?
>
> Are these 3 all equivalent then?
>
> int x(10);
> int x =10;
> int x ={10};
Sort of. In theory, the second is a bit different from the first. The
first directly initializes x with the value 10. The second initializes a
tem****ary with the value 10, then uses the copy ctor to copy that value
into x.
In the case of type int, this doesn't really make any difference -- but
for a user defined type, it can. Even though the compiler can (and
usually will) elide the use of the copy constructor, it still has to be
available. If you defined a class with a public ctor that took an int,
but a private copy constructor, the first would work but the second
would not.
The third is only allowed for aggregates -- basically PODs, though the
two are technically separate. Consider:
class X {
int x;
X(X const &);
public:
X(int value) : x(value) {}
};
int main() {
X x(10); // allowed.
X x = 10; // Fails: copy ctor isn't accessible.
X x = {10}; // Fails: brace initialization only for aggregates.
return 0;
}
Quite a few compilers will let you by with the second (especially if you
don't ask for full compliance) since they'll normally eliminate the copy
construction. I'm not aware of any compilers that allow the third,
though I'll admit I haven't tried to look for them.
--
Later,
Jerry.
The universe is a figment of its own imagination.


|