I have a basic C++ question which I really should know the answer to.
Say we have some class A
with constructor A(int a)
. What is the difference between:
A test_obj(4);
and
A test_obj = A(4);
?
I generally use the latter syntax, but after looking up something unrelated in my trusty C++ primer I realized that they generally use the former. The difference between these two is often discussed in the context of built-in types (eg int a(6)
vs int a = 6
), and my understanding is that in this case they are equivalent.
However, in the case of user-defined classes, are the two approaches to defining an object equivalent? Or is the latter option first default constructing test_obj
, and then using the copy constructor of A
to assign the return value of A(4)
to test_obj
? If it's this second possibility, I imagine there could be some performance differences between the two approaches for large classes.
I'm sure this question is answered somewhere on the internet, even here, but I couldn't search for it effectively without finding questions asking the difference between the first option and using new
, which is unrelated.
A test_obj = A(4);
conceptually does indeed construct a temporary A
object, then copy/move-construct test_obj
from the temporary, and then destruct the temporary.
However this process is a candidate for copy elision which means the compiler is allowed to treat it as A test_obj(4);
after verifying that the copy/move-constructor exists and is accessible.
From C++17 it will be mandatory for compilers to do this; prior to that it was optional but typically compilers did do it.
Performance-wise these are equivalent, even if you have a non-standard copy constructor, as mandated by copy elision . This is guaranteed since C++17 but permitted and widely present even in compilers conforming to earlier standards.
Try for yourself, with all optimizations turned off and the standard forced into C++11 (or C++03, change the command line in the top right): https://godbolt.org/g/GAq7fi
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.