Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct definition vs struct declaration and storage generation

From Scope Regions in C++

In C, a struct declaration never generates storage, so C doesn't distinguish struct definitions from other struct declarations. C++ does. In C++, a struct declaration is also a definition if it has a body, as in:

struct widget   // a definition
    {
    ...
    };

It's only a declaration if it lacks a body, as in:

struct widget; // just a declaration

So in which cases does struct declaration generates storage in c++?

like image 918
q126y Avatar asked Dec 21 '25 13:12

q126y


1 Answers

The following is my paraphrase of the above, hopefully more clear.

struct declarations never generate storage, in either C or C++.

Since C doesn't distinguish struct definitions from other struct declarations, struct definitions never generate storage in C, either.

In C++ the definition of a struct with a static data member (n.b. there is no such thing as a static data member in C) does not generate storage in and by itself, but formally declares its static data member, which is then required to be defined in an enclosing scope - at which point it does in fact generate storage.

In other words, the C++ definition of the struct doesn't technically generate storage, but practically can't be used unless its static data member is defined elsewhere (with the implied storage - even if no objects of that type are ever instantiated).

Relevant C++ references below.

- 3.1.2 Declarations and definitions

struct X { // defines X
    static int y; // declares static data member y
};

int X::y = 1; // defines X::y

- 9.4.2 Static data members

9.4.2.1 [...] A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.

[...] The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void.

[...] The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

[...] Note: once the static data member has been defined, it exists even if no objects of its class have been created.

like image 85
dxiv Avatar answered Dec 24 '25 03:12

dxiv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!