sizeof(struct::member)

R

Rafal Dabrowa

Suppose we have the following structure:

struct foo {
int x, y;
};

Is there a possibility to get sizeof(foo::x) when
no variable of type foo is available ?

I'm not interested with sizeof(int). I want to
express association of sizeof with the variable.


Rafal
 
A

Alf P. Steinbach

* Rafal Dabrowa:
Suppose we have the following structure:

struct foo {
int x, y;
};

Is there a possibility to get sizeof(foo::x) when
no variable of type foo is available ?

A common hack is

foo fooObject(); // Not implemented.

std::size_t const s = sizeof( fooObject().x );

If you like to live dangerously you can alternatively just
cast 0 to a pointer to foo and dereference it, but although
it should be practically safe (sizeof arguments aren't evaluated
at run time) I'm not sure about its formal legality: if it were
all OK then presumably the hack above would be less used.
 
A

Alf P. Steinbach

* Alf P. Steinbach:
* Rafal Dabrowa:

A common hack is

foo fooObject(); // Not implemented.

std::size_t const s = sizeof( fooObject().x );

If you like to live dangerously you can alternatively just
cast 0 to a pointer to foo and dereference it, but although
it should be practically safe (sizeof arguments aren't evaluated
at run time) I'm not sure about its formal legality: if it were
all OK then presumably the hack above would be less used.

Forgot to mention: in your particular example case you don't have
to worry about constructor availability, so you could just write

sizeof( foo().x )

but that won't work in general.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top