How many ways are there to initialize variables? Don't forget to watch out for bugs that look like variable initialization, but aren't.
![]()
Problem
What is the difference, if any, between the following?
SomeType t = u;
SomeType t(u);
SomeType t();
SomeType t;
![]()
Solution
Taking them in reverse order:
声明一个变量, 并使用默认的建构子进行初始化其值。
SomeType t;
The variable t is initialised using the default ctor SomeType::SomeType().
是对函数t的宣告, 并返回一个sometype 的值:
SomeType t();
This was a trick; it might look like a variable declaration, but it's a function declaration for a function t that takes no parameters and returns a SomeType.
声明一个t 变量, 并使用u 对其初始化。
SomeType t(u);
This is direct initialisation. The variable t is initialised using SomeType::SomeType(u).
调用的是赋值构造, 由于是在变量声明阶段, 所以不是赋值。
SomeType t = u;
This is copy initialisation, and the variable t is always initialised using SomeType's copy ctor. (Even though there's an "=" there, that's just a syntax holdover from C... this is always initialisation, never assignment, and so operator= is never called.)
Semantics: If u also has type SomeType, this is the same as "SomeType t(u)" and just calls SomeType's copy ctor. If u is of some other type, then this is the same as "SomeType t( SomeType(u) )"... that is, u is converted to a temporary SomeType object, and t is copy-constructed from that.
Note: The compiler is actually allowed (but not required) to optimize away the copy construction in this kind of situation. If it does optimize it, the copy ctor must still be accessible.
[Guideline] Prefer using the form "SomeType t(u)". It always works wherever "SomeType t = u" works, and has other advantages (for instance, it can take multiple parameters).
本文详细解释了四种不同的变量初始化方式及其区别,包括直接初始化、复制初始化、默认构造初始化及易混淆的函数声明语法。

6356

被折叠的 条评论
为什么被折叠?



