Géry Ogam
Géry Ogam

Reputation: 8027

Is an object a storage location or a value in C++?

In C++, is an object a storage location (container) or a value (content)?

With this sentence from [intro.object]/1, one can assume it is a value (bold emphasis mine):

An object occupies a region of storage in its period of construction ([class.cdtor]), throughout its lifetime, and in its period of destruction ([class.cdtor]).

With this sentence from [basic.types.general]/2, one can assume it is a storage location (bold emphasis mine):

For any object (other than a potentially-overlapping subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]).

Upvotes: 3

Views: 266

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148890

An object is an entity that has a type (a set of operations that can be performed on it) and occupies some allocated storage region with the proper size (given by the operator sizeof) and alignment (given by the operator alignof) for the type. The storage region has an address (given by the operator &) and holds a representation which is a sequence of bytes, a subset of which represents a value. An object finally has a lifetime which starts at the end of its initialization, and ends at the start of its finalization or when its storage region is deallocated or reused by another object.

Using an object outside its lifetime is undefined behaviour.

As a programmer can change the representation of an object at any time by directly accessing its bytes, an object can hold a valid value or not. Invalid values for basic types are known as trap representation and using an object containing such a trap representation is undefined behaviour.

So an object is neither a storage region nor a value, but a complex thing that is called object in C language.

Upvotes: 4

Related Questions