构造和初始化列表:编译器做什么

Construction and initialization list : what the compiler do?

本文关键字:编译器 什么 列表 初始化      更新时间:2023-10-16

我对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"

是的,只有在根本不声明任何构造函数的情况下,才会隐式声明默认构造函数。

相关文章: