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
432 views
in Technique[技术] by (71.8m points)

constructor - C++ Object Instantiation vs Assignment

What is the difference between this:

TestClass t;

And this:

TestClass t = TestClass();

I expected that the second might call the constructor twice and then operator=, but instead it calls the constructor exactly once, just like the first.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
TestClass t;

calls the default constructor.

TestClass t = TestClass();

is a copy initialization. It will call the default constructor for TestClass() and then the copy constructor (theoretically, copying is subject to copy elision). No assignment takes place here.

There's also the notion of direct initialization:

TestClass t(TestClass());

If you want to use the assignment operator:

TestClass t;
TestClass s;
t = s;

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

...