Skip to main content

Command Palette

Search for a command to run...

Size of a non-static member of a class

Published
1 min read

How to get the size of a non-static member of a class without construct that class?

C

sizeof operator:

When applied to an expression, sizeof does not evaluate the expression...

Hence, we can write:

sizeof(((Foo*) 0)->m);

C++

c++0x allow that:

// a more elegant way
sizeof(Foo::m);

expr.prim.id.qual:

A nested-name-specifier that denotes a class, optionally followed by the keyword template ([temp.names]), and then followed by the name of a member of either that class ([class.mem]) or one of its base classes, is a qualified-id; ... The result is an lvalue if the member is a static member function or a data member and a prvalue otherwise.

Reference

Extending sizeof to apply to non-static data members without an object (revision 1)

Getting the size of member variable

More from this blog

簡介 C++ 的 Type Erase (用多型和模板做 Duck Type)

起點 讓我們先從 template 出發:foo 需要一個 callback function。 template<typename Func> void foo(Func callback) { // ... callback(); } 但是這會讓編譯錯誤訊息有點模糊:假如 callback 並不是一個可以呼叫的函數指標,或者並不是一個 callable object ,那編譯器會說錯出在第四行。但是我們都希望,編譯器在呼叫函數時就幫我們指出:這不是 foo 想要的 call...

May 14, 20243 min read

帕秋莉的魔法筆記

45 posts

後端工程師。

不定時張貼一些寫扣時的筆記。

Size of a non-static member of a class