假设我编译了一个包含这段代码的源文件,
struct Point
{
int x;
int y;
};
struct Size
{
int x;
int y;
};
由于Point
和Size
完全相同(就其成员的内存布局而言),编译器是否会struct
在目标文件中生成重复代码(每个代码一个)?这是我的第一个问题。
现在,让我们struct Size
从源代码中删除 ,并使用它来定义它typedef
,就像这样,
typedef Point Size;
现在编译会做什么?它会重复代码吗(因为 typedef 不仅仅是重命名,而不仅仅是重命名)?
现在假设我们有一个这样的类模板:
template <int UnUsed>
class ConcreteError : public BaseError {
public:
ConcreteError () :BaseError(), error_msg() {}
ConcreteError (int errorCode, int osErrorCode, const std::string& errorMessage)
:BaseError(errorCode, osErrorCode, errorMessage){}
};
然后我们设置一些定义,像这样,
typedef ConcreteError<0> FileError;
typedef ConcreteError<1> NetworkError;
typedef ConcreteError<2> DatabaseError;
由于int UnUsed
类的实现中没有使用模板参数(只是假设),所以看起来这种情况与具有完全相同的内存布局的多个类完全相同(类似于struct Point
and的情况struct Size
),是否会出现重复代码目标文件?
如果我们这样做会怎样,
typedef ConcreteError<0> FileError;
typedef ConcreteError<0> NetworkError;
typedef ConcreteError<0> DatabaseError;
这种情况是否更好,因为现在我们在 typedefs 中使用相同的实例化类?
PS:这个类模板代码取自这里:
实际上,我不知道编译器如何从源代码生成目标文件,以及它如何处理类名、成员、其他符号等等。它如何处理 typedef?这有什么用,
typedef int ArrayInt[100];
ArrayInt
这里有新类型吗?什么代码编译器在目标文件中为它创建?存储在哪里100
?