In C++
, is there any semantic difference between the following 3 methods of initialization?
T t;
T t = T();
auto t = T();
I'm interested in differences w.r.t. copy constructor, destructor and assignment operator behavior.
In C++
, is there any semantic difference between the following 3 methods of initialization?
T t;
T t = T();
auto t = T();
I'm interested in differences w.r.t. copy constructor, destructor and assignment operator behavior.
They are not equivalent. The first one leaves t
uninitialized if it's a POD type, whereas the latter two will value-initialize the object no matter what. Example:
#include <iostream>
using namespace std;
int main()
{
int a = int();
cout << a << endl;
return 0;
}
results in:
$ clang++ -O2 -o init init.cpp
$ ./init
0
whereas this:
#include <iostream>
using namespace std;
int main()
{
int a;
cout << a << endl;
return 0;
}
will output some garbage (or crash, or make demons fly out of your nose) since it has undefined behavior arising out of the uninitialized object:
$ clang++ -O2 -o init init.cpp
$ ./init
1348959264
As to the question of copy constructors and assignment operators: the second and third snippets may invoke one of them (or may not, thanks to copy elision), so either of them (or both) need to be available.