类构造函数初始化列表:
使用初始化列表是显式地初始化,否则为赋值
有的时候必须用带有初始化列表的构造函数:
- 成员类型是没有默认构造函数的类。若没有提供显示初始化式,则编译器隐式使用成员类型的默认构造函数,若类没有默认构造函数,则编译器尝试使用默认构造函数将会失败。
- const 成员或引用类型的成员。因为 const 对象或引用类型只能初始化,不能对他们赋值。
class NoDefaultConstructor {
public:
int data;
NoDefaultConstructor(int data) : data(data) {}
};
class ListInitializing {
public:
NoDefaultConstructor noDefaultConstructor;
string &str;
ListInitializing(string str) : noDefaultConstructor(0), str(str) {}
};
int main() {
string str="1,2,3";
ListInitializing listInitializing(str);
ListInitializing listInitializing2("123");
// string &str="123";
string pre="123";
string &str1=string("pre");
当前类的其他对象的pivate成员,对于当前类是可见的
s1, s2 在栈空间,p在堆空间,离开scope后p不会释放,并且无法被访问
内存泄露?
不检测自我赋值,可能会凉
new做的3个动作:
- 调用malloc(void* 指针)
- 转型
- 调用构造函数
pass by reference 不加 const 时,遇到临时变量,不能编译通过
In general, any time you need to write your own custom copy constructor, you also need to write a custom assignment operator.
48,写31,如果还给操作系统,写30
没有人调用getInstance
的话,static A a
不会存在,首次调用后存在于全局空间。
- composition
has-a
组合,适配器模式,
deque可以念diQ或带克
- delegation
composition by reference
- inherence
is-a
函数的继承不应该从内存的角度去理解,而应该从调用权的角度去理解