Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C - C++ Learning > Re: initialisin...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 5 of 5 Topic 4125 of 4250
Post > Topic >>

Re: initialising built in types with curly braces

by Jerry Coffin <jcoffin@[EMAIL PROTECTED] > May 4, 2008 at 01:33 PM

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.
 




 5 Posts in Topic:
initialising built in types with curly braces
Sard <Sardaukary@[EMAI  2008-04-20 15:03:24 
Re: initialising built in types with curly braces
Barry Schwarz <schwarz  2008-04-20 20:59:49 
Re: initialising built in types with curly braces
Ian Collins <ian-news@  2008-04-21 16:02:29 
Re: initialising built in types with curly braces
Ron Natalie <ron@[EMAI  2008-04-23 08:17:10 
Re: initialising built in types with curly braces
Jerry Coffin <jcoffin@  2008-05-04 13:33:10 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Thu Aug 28 5:33:52 CDT 2008.