Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

c++ - When should you use direct initialization and when copy initialization?

Is it simply preference or are there specific instances where one is necessary over another? I'm refering to the following variants for initialization

T t(e); // direct initialization
T t = e; // copy initialization
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The actual names of the things you describe is not implicit and explicit assignment but :

  • Copy-initialization : T x = a;
  • Direct-initialization : T x(a);

They are not equivalent, most notably in contexts where a conversion is required, for example when T is of class type and a is of a different type (see Alf comment for examples of contexts which don't even involve conversion). Consider the following code :

class Test
{
public:
    explicit Test(int i) { /* ... */ }
};

int main()
{
    Test t(0);  // OK : calls Test::Test(int)
    Test u = 0; // KO : constructor is marked explicit
}

To paraphrase the standard (8.5/14) :

  • For direct-initialization and copy-initialization where the source type is the same as, or a derived class of, the class of destination, constructors are considered
  • For other copy-initialization cases, like the second line of main in my example, user-defined conversion sequence are considered. As the use of the Test constructor for implicit conversion was disallowed by the explicit keyword, the second line fails to compile.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...