对于使用用户提供的默认构造函数(未显式初始化任何内容)对结构进行默认和值初始化,不会对 unsigned char 成员执行初始化:
struct uninitialized_char {
unsigned char m;
uninitialized_char() {}
};
// just to be safe
static_assert(1 == sizeof(uninitialized_char), "");
std::vector<uninitialized_char> v(4 * (1<<20));
GetMyDataFromC(reinterpret_cast<unsigned char*>(&v[0]), v.size());
我认为这在严格的别名规则下甚至是合法的。
当我将构建时间v
与 a进行比较时,vector<unsigned char>
我得到了 ~8 µs 和 ~12 ms。速度快 1000 倍以上。编译器是带有 libc++ 和标志的 clang 3.2:-std=c++11 -Os -fcatch-undefined-behavior -ftrapv -pedantic -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-missing-prototypes
C++11 有一个用于未初始化存储的助手,std::aligned_storage。虽然它需要编译时间大小。
这是一个附加示例,用于比较总使用量(以纳秒为单位的时间):
版本=1 ( vector<unsigned char>
):
clang++ -std=c++14 -stdlib=libc++ main.cpp -DVERSION=1 -ftrapv -Weverything -Wno-c++98-compat -Wno-sign-conversion -Wno-sign-compare -Os && ./a.out
initialization+first use: 16,425,554
array initialization: 12,228,039
first use: 4,197,515
second use: 4,404,043
版本=2 ( vector<uninitialized_char>
):
clang++ -std=c++14 -stdlib=libc++ main.cpp -DVERSION=2 -ftrapv -Weverything -Wno-c++98-compat -Wno-sign-conversion -Wno-sign-compare -Os && ./a.out
initialization+first use: 7,523,216
array initialization: 12,782
first use: 7,510,434
second use: 4,155,241
#include <iostream>
#include <chrono>
#include <vector>
struct uninitialized_char {
unsigned char c;
uninitialized_char() {}
};
void foo(unsigned char *c, int size) {
for (int i = 0; i < size; ++i) {
c[i] = '\0';
}
}
int main() {
auto start = std::chrono::steady_clock::now();
#if VERSION==1
using element_type = unsigned char;
#elif VERSION==2
using element_type = uninitialized_char;
#endif
std::vector<element_type> v(4 * (1<<20));
auto end = std::chrono::steady_clock::now();
foo(reinterpret_cast<unsigned char*>(v.data()), v.size());
auto end2 = std::chrono::steady_clock::now();
foo(reinterpret_cast<unsigned char*>(v.data()), v.size());
auto end3 = std::chrono::steady_clock::now();
std::cout.imbue(std::locale(""));
std::cout << "initialization+first use: " << std::chrono::nanoseconds(end2-start).count() << '\n';
std::cout << "array initialization: " << std::chrono::nanoseconds(end-start).count() << '\n';
std::cout << "first use: " << std::chrono::nanoseconds(end2-end).count() << '\n';
std::cout << "second use: " << std::chrono::nanoseconds(end3-end2).count() << '\n';
}
我正在使用 clang svn-3.6.0 r218006