<xstd/misc/type_traits/no_unique_address.hpp>¶
XSTD_NO_UNIQUE_ADDRESS¶
#define XSTD_NO_UNIQUE_ADDRESS see below
A portable spelling of the attribute name that gives [[no_unique_address]]'s semantics. It expands to
msvc::no_unique_address on MSVC, whose standard spelling is layout-neutral, and to no_unique_address elsewhere.
Notes¶
An empty member declared with it needs no storage of its own.
Example¶
Adapted from the example of
[[no_unique_address]] on cppreference.com,
at
revision 174656,
by cppreference.com contributors. This example is under
CC-BY-SA 3.0 and the GFDL, as cppreference.com's content is; the rest of this
page is under the Boost Software License.
#include <xstd/misc/type_traits/empty_member_type.hpp> // empty_member_type
#include <xstd/misc/type_traits/no_unique_address.hpp> // XSTD_NO_UNIQUE_ADDRESS
#include <iostream> // boolalpha, cout
struct Empty
{}; // empty class
struct X
{
int i;
Empty e;
};
struct Y
{
[[XSTD_NO_UNIQUE_ADDRESS]] Empty e;
int i;
};
struct Z
{
char c;
[[XSTD_NO_UNIQUE_ADDRESS]] Empty e1, e2;
};
struct W
{
[[XSTD_NO_UNIQUE_ADDRESS]] xstd::empty_member_type<struct first> e1;
[[XSTD_NO_UNIQUE_ADDRESS]] xstd::empty_member_type<struct second> e2;
char c;
};
auto main() -> int
{
// the size of any object of empty class type is at least 1
static_assert(sizeof(Empty) >= 1);
// at least one more byte is needed to give e a unique address
static_assert(sizeof(X) >= sizeof(int) + 1);
// empty member optimized out
std::cout << "sizeof(Y) == sizeof(int) is " << std::boolalpha << (sizeof(Y) == sizeof(int)) << '\n';
// e1 and e2 cannot share an address, having the same type, but either may share one with c
static_assert(sizeof(Z) >= 2);
// e1 and e2 have different types, so both can share an address with c
std::cout << "sizeof(W) == 1 is " << (sizeof(W) == 1) << '\n';
}
Output:
sizeof(Y) == sizeof(int) is true
sizeof(W) == 1 is true
See also¶
| Entity | Relation |
|---|---|
empty_member_type |
the empty type such a member usually has |
[[no_unique_address]] |
the standard attribute it spells |