English 中文(简体)
空置结构的规模在C和C++中为0,为什么? [复制]
原标题:sizeof empty structure is 0 in C and 1 in C++ why? [duplicate]
This question already has answers here:
Closed 12 years ago.

Possible Duplicates:
Empty class in C++
What is the size of an empty struct in C?

I read somewhere that size of an empty struct in C++ is 1. So I thought of verifying it. Unfortunately I saved it as a C file and used <stdio.h> header and I was surprised to see the output. It was 0.

这意味着:

struct Empty {

};

int main(void)
{
  printf("%d",(int)sizeof(Empty));
}

0 页: 1 汇编成C++文档。 我想知道原因。 页: 1 C++的空洞结构并非零,因为如果大小为<0>0<>>>/代码>,那么该类的两种物体就会有相同的地址,不可能。 我在哪里错了?

问题回答

You cannot have an empty structure in C. It is a syntactic constraint violation. However gcc permits an empty structure in C as an extension. Furthermore the behaviour is undefined if the structure does not have any named member because

说:

如果“方向声明”清单没有指定成员,行为就没有界定。

So

struct Empty {}; //constraint violation

struct Empty {int :0 ;}; //no named member, the behaviour is undefined.

空洞结构的大小是C++

这里是一条可贵的条款,它描述了为什么发生这种情况,更相关的是围绕它采取(安全)的方式:

rel=“noretinger”> http://www.cantrip.org/oneyopt.html





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签