By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,421 Members | 1,053 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,421 IT Pros & Developers. It's quick & easy.

Constructor vs assignment

P: n/a
Hello all,

What, if any, is the difference between

string s("toto");
string s = "toto";

In the first case, I am using the constructor:

basic_string(const value_type *ptr);

In the second case, I believe I first call another constructor:

basic_string();

and then operator= is executed...? Only I don't see any reference to
operator= in my documentation.

I am puzzled.

Nudge

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Grumble" <in*****@kma.eu.org> wrote in message news:bp**********@news-rocq.inria.fr...
In the second case, I believe I first call another constructor:

basic_string();

and then operator= is executed...? Only I don't see any reference to
operator= in my documentation.


No, that isn't correct. The = in the declaration isn't assignment, it's denotes
initialization, specifically copy initialization. The other case is called direct
initialization. The right side of the = is converted
to a temporary of the type of the new object and then direct initalized (via the
copy constructor) to the created object In most cases the compiler
optimizes them to the same code (omitting the unnecessary temporary/copy).
Copy-initialization is left over from C, and is necessary for the brace style
aggregate initialization for which there is no direct-initialization syntax.
Jul 19 '05 #2

P: n/a
"Grumble" <in*****@kma.eu.org> wrote in message
news:bp**********@news-rocq.inria.fr...
| What, if any, is the difference between
|
| string s("toto");
| string s = "toto";
|
| In the first case, I am using the constructor:
|
| basic_string(const value_type *ptr);
|
| In the second case, I believe I first call another constructor:
|
| basic_string();
|
| and then operator= is executed...?
No, but this is a classic confusion.

What happens, in the second case, is that a temporary
may first be created to convert "toto" (the array of char)
into an std::string, and then the copy constructor will
be called, and the temporary destructed.
Many compilers will optimize-out the intermediate copy,
but the copy-constructor still has to be accessible.

By using the direct-initialization syntax, you
ensure that this intermediate copy will not occur.

See also, for some details and terminology:
groups.google.com/groups?selm=bod097%24iiv%241%40newshispeed.ch
hth -Ivan
--
http://ivan.vecerina.com
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.