构造和初始化列表:编译器做什么
Construction and initialization list : what the compiler do?
我对C++中的构造函数有一些问题。对于每个问题(从(1)到(4)),我想知道行为是否与标准完美相关。
A) 第一个是关于成员初始化:
class Class
{
public:
Class()
: _x(0)
, _y(_x)
, _z(_y) // <- (1) Can I initialize a member with other members ?
{
;
}
protected:
int _x;
int _y;
int _z;
};
B) 编译器向每个类添加了哪些函数?
template<typename T> class Class
{
public:
template<typename T0>
Class(const Class<T0>& other)
{
std::cout<<"My copy constructor"<<std::endl;
_x = other._x;
}
template<typename T0 = T>
Class (const T0 var = 0)
{
std::cout<<"My normal constructor"<<std::endl;
_x = var;
}
public:
T _x;
};
// (2) Are
// Class(const Class<T>& other)
// AND
// inline Class<T>& operator=(const Class<T>& other)
// the only functions automatically added by the compiler ?
举个例子,如果我调用:
Class<int> a;
Class<int> b(a); // <- Will not write "My copy constructor"
Class<double> c(a); // <- Will write "My copy constructor"
(3) 按照标准,这种行为完全正常吗?
(4) 我是否保证不会自动添加空构造函数,并且Class<int> x;
将写入"My normal constructor"
?
我可以用其他成员初始化一个成员吗?
是的,只要其他成员已经初始化;即,只要它们的声明在被初始化的成员之前。
[复制构造函数]和[复制赋值运算符]是编译器自动添加的唯一函数吗?
它还将隐式声明一个析构函数,该析构函数将使用其析构函数来销毁_x
。
在C++11中,移动构造函数(Class(Class&&)
)和移动赋值运算符(Class& operator=(Class&&)
)也是隐式声明的,除非您声明了复制或移动构造函数或复制或移动赋值运算符。
请注意,您的构造函数模板是而不是复制构造函数,将使用隐式构造函数:
Class<T1> t1;
Class<T1>(t1); // prints nothing
Class<T2>(t1); // prints "My copy constructor" (which is a lie)
根据标准,这种行为完全正常吗?
是,请参阅第12章。
我是否保证不会自动添加空构造函数,并且
Class<int> x;
将写入"My normal constructor"
?
是的,只有在根本不声明任何构造函数的情况下,才会隐式声明默认构造函数。
相关文章:
- 编译器对数组声明大小的计算。什么时候发生?
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 在使用包含冒号的类似函数的宏时,是什么导致了这种编译器差异?
- 我的设备上的 C++ 编译器版本是什么
- 处理编译器关于可能丢失数据的警告的最优雅方法是什么
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 这个编译器错误究竟希望我执行什么?
- Visual Studio 编译器的 record-gcc-switch 相当于什么?
- 如果字符串在 C/C++ 中没有 NUL 字符(以防编译器允许它通过)会发生什么情况?
- 编译器在这里做什么,允许在很少进行实际比较的情况下比较许多值
- 告诉编译器我希望变量始终存储在寄存器中的正确方法是什么
- openmpi 编译器有什么区别
- 使用不同的编译器 - 这有什么作用
- 编译器遇到返回语句时会做什么
- GCC,Apple LLVM和MSVC编译器的不同部分的名称是什么?
- GCC 编译器对类型转换有什么作用?为什么 mac 和 Linux 上的输出不同
- 编译器认为 int 是一个字符串.发生了什么事情
- 即使使用用户定义的构造函数,编译器什么时候仍会生成默认构造函数
- c++编译器什么时候开始考虑在字符串转义中使用两个以上的十六进制数字?