以下显然有效的代码使用 UndefinedBehaviorSanitizer 清理程序产生未对齐的地址运行时错误。
#include <memory>
#include <functional>
struct A{
std::function<void()> data; // seems to occur only if data is a std::function
} ;
struct B{
char data; // occurs only if B contains a member variable
};
struct C:public virtual A,public B{
};
struct D:public virtual C{
};
void test(){
std::make_shared<D>();
}
int main(){
test();
return 0;
}
在 macbook 上编译和执行
clang++ -fsanitize=undefined --std=c++11 ./test.cpp && ./a.out
会产生输出
runtime error: constructor call on misaligned address 0x7fe584500028 for type 'C', which requires 16 byte alignment [...]
。
我想了解错误发生的方式和原因。