Constructor vs assignment

G

Grumble

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
 
R

Ron Natalie

Grumble said:
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.
 
I

Ivan Vecerina

| 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top