Friday, October 8, 2010

Copy Initialization vs. Direct Initialization

MyClass x; MyClass y(x); is direct initialization.
MyClass x; MyClass y = x; is copy initialization.
Copy Initialization ('=x') creates a temporary, where as Direct Initialization (y(x)) doesn't. Compilers can optimize out this temporary. The Sun CC compiler optimizes out the temporary. Thanks to Srinivas Shilangani for pointing this out. The naming looks like the opposite of that expected, since direct initialization is using the copy constructor. Copy initialization also uses the copy constructor, but it is not explicit.

References: More Exceptional C++ by Herb Sutter. Addison-Wesley, 2002., p. 224. And http://www.gotw.ca/gotw/036.htm


References: More Exceptional C++ by Herb Sutter. Addison-Wesley, 2002., p. 224. And http://www.gotw.ca/gotw/036.htm

No comments:

Post a Comment