在gcc或clang(或任何其他编译器)中是否有一种方法可以吐出有关结构是否有空洞(内存对齐方式)的信息?
谢谢.
ps:如果还有其他办法,请告知我.
有没有办法查看由编译器(如VC++ 2008)为未定义它们的类生成的默认函数(例如,默认复制构造函数,默认赋值运算符)?
这是我的cpp代码.
#include <iostream>
using namespace std;
class A {
public:
int val;
char a;
};
class B: public A {
public:
char b;
};
class C: public B {
public:
char c;
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
程序的输出(在gcc中)是:
8
12
12
Run Code Online (Sandbox Code Playgroud)
这个输出让我很困惑.
我知道对齐可能是sizeof(A)等于8的原因.(sizeof(int) + sizeof(char) + 3 bytes padding)
我还猜测sizeof(B)(sizeof(B) == sizeof(A) + sizeof(char) + 3 bytes padding)的扩展是为了避免重置发生时的重叠.(是对的吗?)
但我真的不知道为什么sizeof(B)等于sizeof(C). …
当使用clang或gcc(在macOS上)编译时,以下代码似乎运行正常,但在使用MS Visual C++ 2017编译时崩溃.在后者上,foo_clone对象似乎已损坏,程序崩溃时出现访问冲突foo_clone->get_identifier().
如果我删除协变返回类型(所有clone-methods返回IDO*),或何时std::enable_shared_from_this删除,或者所有继承都是虚拟的,它确实适用于VC++ .
为什么它适用于clang/gcc而不适用于VC++?
#include <memory>
#include <iostream>
class IDO {
public:
virtual ~IDO() = default;
virtual const char* get_identifier() const = 0;
virtual IDO* clone() const = 0;
};
class DO
: public virtual IDO
, public std::enable_shared_from_this<DO>
{
public:
const char* get_identifier() const override { return "ok"; }
};
class D : public virtual IDO, public DO {
D* clone() const override {
return nullptr;
}
};
class IA …Run Code Online (Sandbox Code Playgroud)