2

I am confused with followed concepts:

string str="123"; 

Some books say that: using "=" is copy initialization,

but some articles say: string str="123" is same as string str("123"). There is no doubt str("123") is directly initialization.

So which style for string str="123";?

How to judge which is copy initialization or directly initialization?

3
  • It all depends on your style of writing code. Commented Apr 25, 2013 at 8:13
  • 1
    See copy initianization. Commented Apr 25, 2013 at 8:21
  • you mean, use '=' is copy initial ? Commented Apr 25, 2013 at 8:22

2 Answers 2

4

It's simply a matter of grammar:

  • T x = y; is copy-initialization, and

  • T x(y); is direct-initialization.

This is true for any type T. What happens exactly depends on what sort of type T is. For primitive types (e.g. ints), the two are exactly the same. For class-types (such as std::string), the two are practically the same, though copy-initialization requires that a copy-constructor be accessible and non-explicit (though it will not actually be called in practice).

Sign up to request clarification or add additional context in comments.

2 Comments

is string str="123" related with copy constructor and be called copy initial?
@jiafu: The grammatical form is "copy initialization". It causes a call to some other, converting constructor, though, which takes a char const *. In principle, there could be two constructor calls, conversion followed by copying, but the second one is usually elided.
0

Yes that is called copy initialization.

Instead of default constructing str and then constructing another string from "123" using string(const char*) and then assigning the two strings, the compiler just construct a string using string(const char*) with "123".

string str="123" is same as string str("123"). There is no doubt str("123") is directly initial

However remember that is possible only if the corresponding constructor is not explicit.

3 Comments

is string str="123" related with copy constructor and be called copy initial?
@jiafu - Yes, it is "related" to the copy constructor, as there formally is a copy involved, but the compiler will optimize that out. If you have a user defined class with constructors that are explicit, private, or delete'ed, you might notice a difference. For std::string that is not the case.
@jiafu You can get a more detailed info on the link I have provided it covers when and how copy initialization is used.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.