当有buffer随后会被覆盖,所以一开始的初始化没有意义的时候,要小心AAA带来的额外性能损耗
auto s = S()
without ctor
struct S {
void foo();
private:
char buf[1024];
};
void foo() {
auto s = S{}; // value initialization
s.foo();
}
S
中的buf
此时会被初始化成全0值
foo(): # @foo()
push rbx
sub rsp, 1024
mov rbx, rsp # zero out buf
mov edx, 1024. #
mov rdi, rbx #
xor esi, esi #
call memset@PLT #
mov rdi, rbx
call S::foo()
add rsp, 1024
pop rbx
ret
因为auto s = S()
的形式是value initialization
,此时
the object is zero-initialized
auto s = S()
with defaulted ctor
struct S {
S() = default;
void foo();
private:
char buf[1024];
};
void foo() {
auto s = S{};
s.foo();
}
结果和上面一样,因为
if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor
auto s = S()
with user-provided empty ctor
struct S {
S() {}
void foo();
private:
char buf[1024];
};
void foo() {
auto s = S{};
s.foo();
}
此时buf
不会初始化
foo(): # @foo()
sub rsp, 1032
lea rdi, [rsp + 8]
call S::foo()
add rsp, 1032
ret
if T is a class type with at least one user-provided constructor of any kind, the default constructor is called
而此时默认构造函数没有初始化buf
S s
without ctor
struct S {
void foo();
private:
char buf[1024];
};
void foo() {
S s; // default initialization
s.foo();
}
此时buf
不会被初始化