c++里的各类初始化
c++中存在的各类初始化
总结一下c++中存在的各类初始化问题, 傻逼c++居然有8种初始化的方式。
- Default-initialization: zero-initialization
- Zero-initialization: value-initialization, non-local initialization, constant-initialization
- Value-initialization: aggregate-initialization, list-initialization, default-initialization, zero-initialization, copy-initialization
- Aggregate-initialization: list-initialization, copy-initialization, direct-initialization
- List-initialization: direct-list-initialization, copy-list-initialization, aggregate-initialization, copy-initialization, direct-initialization
- Direct-initialization: list-initialization, aggregate-initialization, value-initialization, copy-initialization
- Copy-initialization: list-initialization, aggregate-initialization, direct-initialization
- Constant-initialization: default-initialization
- Reference initialization: list-initialization, copy-initialization, direct-initialization
看完感受就两点,第一点,避免默认初始化,第二点,尽量不要用引用的直接初始化延长生命周期,但比较尴尬的是这种操作只能发生一次,引用的传递不会延长生命周期,不要赌编译器行为。
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
int& fun() {
int a = 66;
return a;
}
int main() {
auto b = fun();
}
像上面这种就活不过func call
REF
This post is licensed under CC BY 4.0 by the author.