Post

c++里的各类初始化

c++中存在的各类初始化

总结一下c++中存在的各类初始化问题, 傻逼c++居然有8种初始化的方式。

  1. Default-initialization: zero-initialization
  2. Zero-initialization: value-initialization, non-local initialization, constant-initialization
  3. Value-initialization: aggregate-initialization, list-initialization, default-initialization, zero-initialization, copy-initialization
  4. Aggregate-initialization: list-initialization, copy-initialization, direct-initialization
  5. List-initialization: direct-list-initialization, copy-list-initialization, aggregate-initialization, copy-initialization, direct-initialization
  6. Direct-initialization: list-initialization, aggregate-initialization, value-initialization, copy-initialization
  7. Copy-initialization: list-initialization, aggregate-initialization, direct-initialization
  8. Constant-initialization: default-initialization
  9. 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

  1. C++的各种初始化方式
  2. When and how variables are initialized? Part 1
  3. When and how variables are initialized? Part 2
  4. When and how variables are initialized? - Part 3
  5. When and how variables are initialized? - Part 4
This post is licensed under CC BY 4.0 by the author.

Trending Tags