C++面试题
犹豫了很久,决定开一篇博文专门总结一下C++相关的知识,感觉现在网上很多C++相关的面经总结或者知识讲解都很细碎。对于一些常见的知识并没有做整理,大多数为了起到面试参考的作用写成了FAQ的形式。这样其实并不适合长久学习。
按照cppreference的分类对现有的一些知识做一些基础的总结。
今天我们先从一个小的方面来开始讨论:初始化。
cppreference中提供了各种初始化方法。
默认初始化
当一个被构造的对象没有通过构造函数构造时,我们称之为默认初始化。
- 当声明一个没有构造函数的对象时。
T object;
- 当通过new创造一个没有构造函数的对象时。
new T;
- 当我们在一个类的列表构造函数中没有提及某个基类或者非static成员变量时。
class T:Base{
int val;
T():{}
};
关于默认初始化,我们需要注意:
- if
T
is a (possibly cv-qualified) non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;- if
T
is an array type, every element of the array is default-initialized;- otherwise, no initialization is performed: the objects with automatic storage duration (and their subobjects) contain indeterminate values.
加粗地方的意思简单来说就是,如果我们在非全局作用域下默认初始化了一个内置变量,将会导致一个UB(Cpp prime中有提及)。
值初始化
当一个对象由一个不含参数的初始化函数初始化。
- 直接初始化
- 拷贝初始化
- 列表初始化
- 聚合初始化
- 引用初始化