[basic.memobj] (original) (raw)
6 Basics [basic]
6.7 Memory and objects [basic.memobj]
6.7.1 Memory model [intro.memory]
The fundamental storage unit in the C++ memory model is thebyte.
A byte is at least large enough to contain the ordinary literal encoding of any element of the basicliteral character set ([lex.charset]) and the eight-bit code units of the UnicodeUTF-8 encoding form and is composed of a contiguous sequence of bits,19the number of which is implementation-defined.
The memory available to a C++ program consists of one or more sequences of contiguous bytes.
Every byte has a unique address.
A memory location is the storage occupied by the object representation of either an object of scalar type that is not a bit-field or a maximal sequence of adjacent bit-fields all having nonzero width.
[Note 2:
Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation.
— _end note_]
Two or more threads of execution can access separate memory locations without interfering with each other.
[Note 3:
Thus a bit-field and an adjacent non-bit-field are in separate memory locations, and therefore can be concurrently updated by two threads of execution without interference.
The same applies to two bit-fields, if one is declared inside a nested struct declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field declaration.
It is not safe to concurrently update two bit-fields in the same struct if all fields between them are also bit-fields of nonzero width.
— _end note_]
[Example 1:
A class declared asstruct { char a;int b:5, c:11,:0, d:8;struct {int ee:8;} e;};contains four separate memory locations: The member a and bit-fieldsd and e.ee are each separate memory locations, and can be modified concurrently without interfering with each other.
The bit-fieldsb and c together constitute the fourth memory location.
The bit-fields b and c cannot be concurrently modified, butb and a, for example, can be.
— _end example_]
6.7.2 Object model [intro.object]
The constructs in a C++ program create, destroy, refer to, access, and manipulate objects.
An object is created by a definition, by a new-expression ([expr.new]), by an operation that implicitly creates objects (see below), when implicitly changing the active member of a union, or when a temporary object is created ([conv.rval], [class.temporary]).
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]).
[Note 1:
A function is not an object, regardless of whether or not it occupies storage in the way that objects do.
— _end note_]
The properties of an object are determined when the object is created.
An object has a storage duration ([basic.stc]) which influences its lifetime ([basic.life]).
[Note 2:
Some objects are polymorphic ([class.virtual]); the implementation generates information associated with each such object that makes it possible to determine that object's type during program execution.
— _end note_]
Objects can contain other objects, called subobjects.
An object that is not a subobject of any other object is called a complete object.
If an object is created in storage associated with a member subobject or array element e(which may or may not be within its lifetime), the created object is a subobject of e's containing object if
- the lifetime of e's containing object has begun and not ended, and
- the storage for the new object exactly overlays the storage location associated with e, and
- the new object is of the same type as e (ignoring cv-qualification).
If a complete object is created ([expr.new]) in storage associated with another object _e_of type “array of N unsigned char” or of type “array of N std::byte” ([cstddef.syn]), that array provides storagefor the created object if
- the lifetime of e has begun and not ended, and
- the storage for the new object fits entirely within e, and
- there is no array object that satisfies these constraints nested within e.
[Note 3:
If that portion of the array previously provided storage for another object, the lifetime of that object ends because its storage was reused ([basic.life]).
— _end note_]
[Example 1: template<typename ...T> struct AlignedUnion { alignas(T...) unsigned char data[max(sizeof(T)...)];};int f() { AlignedUnion<int, char> au;int *p = new (au.data) int; char *c = new (au.data) char(); char *d = new (au.data + 1) char();return *c + *d; } struct A { unsigned char a[32]; };struct B { unsigned char b[16]; };alignas(int) A a; B *b = new (a.a + 8) B; int *p = new (b->b + 4) int; — _end example_]
An object a is nested within another object b if
- a is a subobject of b, or
- b provides storage for a, or
- there exists an object _c_where a is nested within c, and c is nested within b.
For every object x, there is some object called thecomplete object of x, determined as follows:
- If x is a complete object, then the complete object of x is itself.
- Otherwise, the complete object of x is the complete object of the (unique) object that contains x.
If a complete object, a member subobject, or an array element is of class type, its type is considered the most derived class, to distinguish it from the class type of any base class subobject; an object of a most derived class type or of a non-class type is called amost derived object.
A potentially-overlapping subobject is either:
- a base class subobject, or
- a non-static data member declared with the no_unique_address attribute.
An object has nonzero size if it
- is not a potentially-overlapping subobject, or
- is not of class type, or
- is of a class type with virtual member functions or virtual base classes, or
- has subobjects of nonzero size or unnamed bit-fields of nonzero length.
Otherwise, if the object is a base class subobject of a standard-layout class type with no non-static data members, it has zero size.
Otherwise, the circumstances under which the object has zero size are implementation-defined.
Unless it is a bit-field, an object with nonzero size shall occupy one or more bytes of storage, including every byte that is occupied in full or in part by any of its subobjects.
An object of trivially copyable or standard-layout type ([basic.types.general]) shall occupy contiguous bytes of storage.
An object is a potentially non-unique object if it is a string literal object ([lex.string]), the backing array of an initializer list ([dcl.init.ref]), or a subobject thereof.
Unless an object is a bit-field or a subobject of zero size, the address of that object is the address of the first byte it occupies.
Two objects with overlapping lifetimes that are not bit-fields may have the same address if
- one is nested within the other,
- at least one is a subobject of zero size and they are not of similar types ([conv.qual]), or
- they are both potentially non-unique objects;
otherwise, they have distinct addresses and occupy disjoint bytes of storage.20
[Example 2: static const char test1 = 'x';static const char test2 = 'x';const bool b = &test1 != &test2; static const char (&r) [] = "x";static const char *s = "x";static std::initializer_list<char> il = { 'x' };const bool b2 = r != il.begin(); const bool b3 = r != s; const bool b4 = il.begin() != &test1; const bool b5 = r != &test1; — _end example_]
The address of a non-bit-field subobject of zero size is the address of an unspecified byte of storage occupied by the complete object of that subobject.
Some operations are described asimplicitly creating objectswithin a specified region of storage.
For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types ([basic.types.general]) in its specified region of storage if doing so would result in the program having defined behavior.
If no such set of objects would give the program defined behavior, the behavior of the program is undefined.
If multiple such sets of objects would give the program defined behavior, it is unspecified which such set of objects is created.
[Note 4:
Such operations do not start the lifetimes of subobjects of such objects that are not themselves of implicit-lifetime types.
— _end note_]
Further, after implicitly creating objects within a specified region of storage, some operations are described as producing a pointer to asuitable created object.
These operations select one of the implicitly-created objects whose address is the address of the start of the region of storage, and produce a pointer value that points to that object, if that value would result in the program having defined behavior.
If no such pointer value would give the program defined behavior, the behavior of the program is undefined.
If multiple such pointer values would give the program defined behavior, it is unspecified which such pointer value is produced.
[Example 3: #include <cstdlib> struct X { int a, b; }; X *make_x() { X *p = (X*)std::malloc(sizeof(struct X)); p->a = 1; p->b = 2;return p;} — _end example_]
Except during constant evaluation, an operation that begins the lifetime of an array of unsigned char or std::byteimplicitly creates objects within the region of storage occupied by the array.
[Note 5:
The array object provides storage for these objects.
— _end note_]
Except during constant evaluation, any implicit or explicit invocation of a function named operator new or operator new[]implicitly creates objects in the returned region of storage and returns a pointer to a suitable created object.
6.7.3 Alignment [basic.align]
Object types have alignment requirements ([basic.fundamental], [basic.compound]) which place restrictions on the addresses at which an object of that type may be allocated.
An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.
An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier ([dcl.align]).
Attempting to create an object ([intro.object]) in storage that does not meet the alignment requirements of the object's type is undefined behavior.
A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal toalignof(std::max_align_t) ([support.types]).
The alignment required for a type may be different when it is used as the type of a complete object and when it is used as the type of a subobject.
[Example 1: struct B { long double d; };struct D : virtual B { char c; };
When D is the type of a complete object, it will have a subobject of type B, so it must be aligned appropriately for a long double.
If D appears as a subobject of another object that also has Bas a virtual base class, the B subobject might be part of a different subobject, reducing the alignment requirements on the D subobject.
— _end example_]
The result of the alignof operator reflects the alignment requirement of the type in the complete-object case.
An extended alignment is represented by an alignment greater than alignof(std::max_align_t).
It is implementation-defined whether any extended alignments are supported and the contexts in which they are supported ([dcl.align]).
A type having an extended alignment requirement is an over-aligned type.
[Note 1:
Every over-aligned type is or contains a class type to which extended alignment applies (possibly through a non-static data member).
— _end note_]
A new-extended alignment is represented by an alignment greater than __STDCPP_DEFAULT_NEW_ALIGNMENT__ ([cpp.predefined]).
Alignments are represented as values of the type std::size_t.
Valid alignments include only those values returned by an alignofexpression for the fundamental types plus an additional implementation-defined set of values, which may be empty.
Every alignment value shall be a non-negative integral power of two.
Alignments have an order from weaker tostronger or stricter alignments.
Stricter alignments have larger alignment values.
An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.
The alignment requirement of a complete type can be queried using analignof expression ([expr.alignof]).
Furthermore, the narrow character types ([basic.fundamental]) shall have the weakest alignment requirement.
[Note 2:
This enables the ordinary character types to be used as the underlying type for an aligned memory area ([dcl.align]).
— _end note_]
Comparing alignments is meaningful and provides the obvious results:
- Two alignments are equal when their numeric values are equal.
- Two alignments are different when their numeric values are not equal.
- When an alignment is larger than another it represents a stricter alignment.
[Note 3:
The runtime pointer alignment function ([ptr.align]) can be used to obtain an aligned pointer within a buffer; an alignment-specifier ([dcl.align]) can be used to align storage explicitly.
— _end note_]
If a request for a specific extended alignment in a specific context is not supported by an implementation, the program is ill-formed.
6.7.4 Lifetime [basic.life]
In this subclause, “before” and “after” refer to the “happens before” relation ([intro.multithread]).
The lifetime of an object or reference is a runtime property of the object or reference.
A variable is said to have vacuous initializationif it is default-initialized, no other initialization is performed, and, if it is of class type or a (possibly multidimensional) array thereof, a trivial constructor of that class type is selected for the default-initialization.
The lifetime of an object o of type T ends when:
- if T is a non-class type, the object is destroyed, or
- if T is a class type, the destructor call starts, or
- the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).
When evaluating a new-expression, storage is considered reused after it is returned from the allocation function, but before the evaluation of the new-initializer ([expr.new]).
[Example 1: struct S { int m;};void f() { S x{1};new(&x) S(x.m); } — _end example_]
The lifetime of a reference begins when its initialization is complete.
The lifetime of a reference ends as if it were a scalar object requiring storage.
[Note 1:
[class.base.init]describes the lifetime of base and member subobjects.
— _end note_]
The properties ascribed to objects and references throughout this document apply for a given object or reference only during its lifetime.
[Note 2:
In particular, before the lifetime of an object starts and after its lifetime ends there are significant restrictions on the use of the object, as described below, in [class.base.init], and in [class.cdtor].
Also, the behavior of an object under construction and destruction can differ from the behavior of an object whose lifetime has started and not ended.
[class.base.init]and [class.cdtor] describe the behavior of an object during its periods of construction and destruction.
— _end note_]
A program may end the lifetime of an object of class type without invoking the destructor, by reusing or releasing the storage as described above.
In this case, the destructor is not implicitly invoked.
[Note 4:
The correct behavior of a program often depends on the destructor being invoked for each object of class type.
— _end note_]
Before the lifetime of an object has started but after the storage which the object will occupy has been allocated21or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that represents the address of the storage location where the object will be or was located may be used but only in limited ways.
For an object under construction or destruction, see [class.cdtor].
Otherwise, such a pointer refers to allocated storage ([basic.stc.dynamic.allocation]), and using the pointer as if the pointer were of type void* is well-defined.
Indirection through such a pointer is permitted but the resulting lvalue may only be used in limited ways, as described below.
The program has undefined behavior if
- the pointer is used as the operand of a delete-expression,
- the pointer is used to access a non-static data member or call a non-static member function of the object, or
- the pointer is implicitly converted ([conv.ptr]) to a pointer to a virtual base class, or
- the pointer is used as the operand of astatic_cast ([expr.static.cast]), except when the conversion is to pointer to cv void, or to pointer to cv void and subsequently to pointer tocv char,cv unsigned char, orcv std::byte ([cstddef.syn]), or
- the pointer is used as the operand of adynamic_cast ([expr.dynamic.cast]).
[Example 2: #include <cstdlib> struct B { virtual void f();void mutate();virtual ~B();};struct D1 : B { void f(); };struct D2 : B { void f(); };void B::mutate() { new (this) D2; f(); ... = this; } void g() { void* p = std::malloc(sizeof(D1) + sizeof(D2)); B* pb = new (p) D1; pb->mutate();*pb; void* q = pb; pb->f(); } — _end example_]
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways.
For an object under construction or destruction, see [class.cdtor].
Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.allocation]), and using the properties of the glvalue that do not depend on its value is well-defined.
The program has undefined behavior if
- the glvalue is used to access the object, or
- the glvalue is used to call a non-static member function of the object, or
- the glvalue is bound to a reference to a virtual base class ([dcl.init.ref]), or
- the glvalue is used as the operand of adynamic_cast ([expr.dynamic.cast]) or as the operand oftypeid.
[Note 5:
Therefore, undefined behavior results if an object that is being constructed in one thread is referenced from another thread without adequate synchronization.
— _end note_]
An object is transparently replaceable by an object if
- the storage that occupies exactly overlays the storage that occupied, and
- and are of the same type (ignoring the top-level cv-qualifiers), and
- is not a const, complete object, and
- neither nor is a potentially-overlapping subobject ([intro.object]), and
- either and are both complete objects, or and are direct subobjects of objects and , respectively, and is transparently replaceable by .
After the lifetime of an object has ended and before the storage which the object occupied is reused or released, if a new object is created at the storage location which the original object occupied and the original object was transparently replaceable by the new object, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object.
[Example 3: struct C { int i;void f();const C& operator=( const C& );};const C& C::operator=( const C& other) { if ( this != &other ) { this->~C(); new (this) C(other); f(); } return *this;}C c1; C c2; c1 = c2; c1.f(); — _end example_]
[Note 6:
If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std::launder ([ptr.launder]).
— _end note_]
If a program ends the lifetime of an object of type T with static ([basic.stc.static]), thread ([basic.stc.thread]), or automatic ([basic.stc.auto]) storage duration and if T has a non-trivial destructor,22and another object of the original type does not occupy that same storage location when the implicit destructor call takes place, the behavior of the program is undefined.
This is true even if the block is exited with an exception.
[Example 4: class T { };struct B { ~B();};void h() { B b;new (&b) T;} — _end example_]
Creating a new object within the storage that a const, complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.
[Example 5: struct B { B();~B();};const B b;void h() { b.~B();new (const_cast<B*>(&b)) const B; } — _end example_]
6.7.5 Indeterminate and erroneous values [basic.indet]
When storage for an object with automatic or dynamic storage duration is obtained, the bytes comprising the storage for the object have the following initial value:
- If the object has dynamic storage duration, or is the object associated with a variable or function parameter whose first declaration is marked with the [[indeterminate]] attribute ([dcl.attr.indet]), the bytes have indeterminate values;
- otherwise, the bytes have erroneous values, where each value is determined by the implementation independently of the state of the program.
If no initialization is performed for an object (including subobjects), such a byte retains its initial value until that value is replaced ([dcl.init.general], [expr.assign]).
If any bit in the value representation has an indeterminate value, the object has an indeterminate value; otherwise, if any bit in the value representation has an erroneous value, the object has an erroneous value ([conv.lval]).
[Note 1:
Objects with static or thread storage duration are zero-initialized, see [basic.start.static].
— _end note_]
Except in the following cases, if an indeterminate value is produced by an evaluation, the behavior is undefined, and if an erroneous value is produced by an evaluation, the behavior is erroneous and the result of the evaluation is the value so produced but is not erroneous:
- If an indeterminate or erroneous value of unsigned ordinary character type or std::byte type is produced by the evaluation of the right operand of a simple assignment operator ([expr.assign]) whose first operand is an lvalue of unsigned ordinary character type or std::byte type, an indeterminate value or that erroneous value, respectively, replaces the value of the object referred to by the left operand.
- If an indeterminate or erroneous value of unsigned ordinary character type is produced by the evaluation of the initialization expression when initializing an object of unsigned ordinary character type, that object is initialized to an indeterminate value or that erroneous value, respectively.
- If an indeterminate value of unsigned ordinary character type or std::byte type is produced by the evaluation of the initialization expression when initializing an object of std::byte type, that object is initialized to an indeterminate value or that erroneous value, respectively.
Converting an indeterminate or erroneous value of unsigned ordinary character type or std::byte type produces an indeterminate or erroneous value, respectively.
In the latter case, the result of the conversion is the value of the converted operand.
[Example 1: int f(bool b) { unsigned char *c = new unsigned char;unsigned char d = *c; int e = d; return b ? d : 0; } int g(bool b) { unsigned char c;unsigned char d = c; assert(c == d); int e = d; return b ? d : 0; } void h() { int d1, d2;int e1 = d1; int e2 = d1; assert(e1 == e2); assert(e1 == d1); assert(e2 == d1); std::memcpy(&d2, &d1, sizeof(int)); assert(e1 == d2); assert(e2 == d2); } — _end example_]
6.7.6 Storage duration [basic.stc]
6.7.6.1 General [basic.stc.general]
The storage duration is the property of an object that defines the minimum potential lifetime of the storage containing the object.
The storage duration is determined by the construct used to create the object and is one of the following:
- static storage duration
- thread storage duration
- automatic storage duration
- dynamic storage duration
[Note 1:
After the duration of a region of storage has ended, the use of pointers to that region of storage is limited ([basic.compound]).
— _end note_]
Static, thread, and automatic storage durations are associated with objects introduced by declarations ([basic.def]) and with temporary objects ([class.temporary]).
The dynamic storage duration is associated with objects created by anew-expression ([expr.new]) or with implicitly created objects ([intro.object]).
The storage duration categories apply to references as well.
The storage duration of subobjects and reference members is that of their complete object ([intro.object]).
6.7.6.2 Static storage duration [basic.stc.static]
All variables which
- do not have thread storage duration and
- belong to a namespace scope ([basic.scope.namespace]) or are first declared with the static or extern keywords ([dcl.stc])
If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in [class.copy.elision].
[Note 1:
The keyword static can be used to declare a block variable ([basic.scope.block]) with static storage duration;[stmt.dcl] and [basic.start.term] describe the initialization and destruction of such variables.
The keyword static applied to a class data member in a class definition gives the data member static storage duration ([class.static.data]).
— _end note_]
6.7.6.3 Thread storage duration [basic.stc.thread]
All variables declared with the thread_local keyword havethread storage duration.
The storage for these entities lasts for the duration of the thread in which they are created.
There is a distinct object or reference per thread, and use of the declared name refers to the entity associated with the current thread.
6.7.6.4 Automatic storage duration [basic.stc.auto]
Variables that belong to a block scope and are not explicitly declared static, thread_local, or extern haveautomatic storage duration.
The storage for such variables lasts until the block in which they are created exits.
[Note 1:
These variables are initialized and destroyed as described in [stmt.dcl].
— _end note_]
Variables that belong to a parameter scope also have automatic storage duration.
The storage for a function parameter lasts until immediately after its destruction ([expr.call]).
If a variable with automatic storage duration has initialization or a destructor with side effects, an implementation shall not destroy it before the end of its block nor eliminate it as an optimization, even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in [class.copy.elision].
6.7.6.5 Dynamic storage duration [basic.stc.dynamic]
6.7.6.5.1 General [basic.stc.dynamic.general]
A C++ implementation provides access to, and management of, dynamic storage via the global allocation functions operator new andoperator new[] and the global deallocation functions operator delete andoperator delete[].
[Note 1:
The non-allocating forms described in [new.delete.placement]do not perform allocation or deallocation.
— _end note_]
The library provides default definitions for the global allocation and deallocation functions.
Some global allocation and deallocation functions are replaceable ([dcl.fct.def.replace]).
The following allocation and deallocation functions ([support.dynamic]) are implicitly declared in global scope in each translation unit of a program.
void* operator new(std::size_t);void* operator new(std::size_t, std::align_val_t);void operator delete(void*) noexcept;void operator delete(void*, std::size_t) noexcept;void operator delete(void*, std::align_val_t) noexcept;void operator delete(void*, std::size_t, std::align_val_t) noexcept;void* operator new[](std::size_t);void* operator new[](std::size_t, std::align_val_t);void operator delete[](void*) noexcept;void operator delete[](void*, std::size_t) noexcept;void operator delete[](void*, std::align_val_t) noexcept;void operator delete[](void*, std::size_t, std::align_val_t) noexcept;
These implicit declarations introduce only the function namesoperator new,operator new[],operator delete, andoperator delete[].
[Note 2:
The implicit declarations do not introduce the names std,std::size_t,std::align_val_t, or any other names that the library uses to declare these names.
Thus, a new-expression,delete-expression, or function call that refers to one of these functions without importing or including the header or importing a C++ library module ([std.modules]) is well-formed.
— _end note_]
Allocation and/or deallocation functions may also be declared and defined for any class ([class.free]).
If the behavior of an allocation or deallocation function does not satisfy the semantic constraints specified in [basic.stc.dynamic.allocation]and [basic.stc.dynamic.deallocation], the behavior is undefined.
6.7.6.5.2 Allocation functions [basic.stc.dynamic.allocation]
An allocation function that is not a class member function shall belong to the global scope and not have a name with internal linkage.
The return type shall be void*.
The first parameter shall have type std::size_t ([support.types]).
The first parameter shall not have an associated default argument ([dcl.fct.default]).
The value of the first parameter is interpreted as the requested size of the allocation.
An allocation function can be a function template.
Such a template shall declare its return type and first parameter as specified above (that is, template parameter types shall not be used in the return type and first parameter type).
Allocation function templates shall have two or more parameters.
An allocation function attempts to allocate the requested amount of storage.
If it is successful, it returns the address of the start of a block of storage whose length in bytes is at least as large as the requested size.
The order, contiguity, and initial value of storage allocated by successive calls to an allocation function are unspecified.
Even if the size of the space requested is zero, the request can fail.
If the request succeeds, the value returned by a replaceable allocation function is a non-null pointer value ([basic.compound])p0 different from any previously returned value p1, unless that value p1 was subsequently passed to a replaceable deallocation function.
Furthermore, for the library allocation functions in [new.delete.single] and [new.delete.array],p0 represents the address of a block of storage disjoint from the storage for any other object accessible to the caller.
The effect of indirecting through a pointer returned from a request for zero size is undefined.23
For an allocation function other than a reserved placement allocation function ([new.delete.placement]), the pointer returned on a successful call shall represent the address of storage that is aligned as follows:
- If the allocation function takes an argument of type std::align_val_t, the storage will have the alignment specified by the value of this argument.
- Otherwise, if the allocation function is named operator new[], the storage is aligned for any object that does not have new-extended alignment ([basic.align]) and is no larger than the requested size.
- Otherwise, the storage is aligned for any object that does not have new-extended alignment and is of the requested size.
An allocation function that fails to allocate storage can invoke the currently installed new-handler function ([new.handler]), if any.
[Note 1:
A program-supplied allocation function can obtain the currently installed new_handler using thestd::get_new_handler function ([get.new.handler]).
— _end note_]
An allocation function that has a non-throwing exception specification ([except.spec]) indicates failure by returning a null pointer value.
Any other allocation function never returns a null pointer value and indicates failure only by throwing an exception ([except.throw]) of a type that would match a handler ([except.handle]) of typestd::bad_alloc ([bad.alloc]).
A global allocation function is only called as the result of a new expression, or called directly using the function callsyntax, or called indirectly to allocate storage for a coroutine state ([dcl.fct.def.coroutine]), or called indirectly through calls to the functions in the C++ standard library.
[Note 2:
In particular, a global allocation function is not called to allocate storage for objects with static storage duration ([basic.stc.static]), for objects or references with thread storage duration ([basic.stc.thread]), for objects of type std::type_info ([expr.typeid]), for an object of type std::contracts::contract_violationwhen a contract violation occurs ([basic.contract.eval]), or for an exception object ([except.throw]).
— _end note_]
6.7.6.5.3 Deallocation functions [basic.stc.dynamic.deallocation]
A deallocation function that is not a class member function shall belong to the global scope and not have a name with internal linkage.
A deallocation function is a destroying operator deleteif it has at least two parameters and its second parameter is of type std::destroying_delete_t.
A destroying operator delete shall be a class member function named operator delete.
[Note 1:
Array deletion cannot use a destroying operator delete.
— _end note_]
Each deallocation function shall return void.
If the function is a destroying operator delete declared in class type C, the type of its first parameter shall be C*; otherwise, the type of its first parameter shall be void*.
A deallocation function may have more than one parameter.
A usual deallocation function is a deallocation function whose parameters after the first are
- optionally, a parameter of type std::destroying_delete_t, then
- optionally, a parameter of type std::size_t,24then
- optionally, a parameter of type std::align_val_t.
A destroying operator delete shall be a usual deallocation function.
A deallocation function may be an instance of a function template.
Neither the first parameter nor the return type shall depend on a template parameter.
A deallocation function template shall have two or more function parameters.
A template instance is never a usual deallocation function, regardless of its signature.
If a deallocation function terminates by throwing an exception, the behavior is undefined.
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value ([basic.compound]), the deallocation function shall deallocate the storage referenced by the pointer, ending the duration of the region of storage.
6.7.7 Temporary objects [class.temporary]
Temporary objects are created
- when a prvalue is converted to an xvalue ([conv.rval]) and
- when needed by the implementation to pass or return an object of suitable type (see below).
Even when the creation of the temporary object is unevaluated ([expr.context]), all the semantic restrictions shall be respected as if the temporary object had been created and later destroyed.
[Note 1:
This includes accessibility ([class.access]) and whether it is deleted, for the constructor selected and for the destructor.
However, in the special case of the operand of adecltype-specifier ([dcl.type.decltype]), no temporary is introduced, so the foregoing does not apply to such a prvalue.
— _end note_]
The materialization of a temporary object is generally delayed as long as possible in order to avoid creating unnecessary temporary objects.
[Note 2:
Temporary objects are materialized:
- when binding a reference to a prvalue ([dcl.init.ref], [expr.type.conv], [expr.dynamic.cast], [expr.static.cast], [expr.const.cast], [expr.cast]),
- when performing certain member accesses on a class prvalue ([expr.ref], [expr.mptr.oper]),
- when invoking an implicit object member function on a class prvalue ([expr.call]),
- when performing an array-to-pointer conversion or subscripting on an array prvalue ([conv.array], [expr.sub]),
- when initializing an object of type std::initializer_list<T> from a braced-init-list ([dcl.init.list]),
- for certain unevaluated operands ([expr.typeid], [expr.sizeof]), and
- when a prvalue that has type other than cv void appears as a discarded-value expression ([expr.context]).
— _end note_]
[Example 1:
Consider the following code:class X { public: X(int); X(const X&); X& operator=(const X&);~X();};class Y { public: Y(int); Y(Y&&);~Y();}; X f(X); Y g(Y);void h() { X a(1); X b = f(X(2)); Y c = g(Y(3)); a = f(a);}
X(2) is constructed in the space used to hold f()'s argument andY(3) is constructed in the space used to hold g()'s argument.
Likewise,f()'s result is constructed directly in b andg()'s result is constructed directly in c.
On the other hand, the expressiona = f(a)requires a temporary for the result of f(a), which is materialized so that the reference parameter of X::operator=(const X&) can bind to it.
— _end example_]
When an object of class type Xis passed to or returned from a potentially-evaluated function call, if X is
- a scalar type or
- a class type that has at least one eligible copy or move constructor ([special]), where each such constructor is trivial, and the destructor of X is either trivial or deleted,
implementations are permitted to create temporary objects to hold the function parameter or result object, as follows:
- The first such temporary object is constructed from the function argument or return value, respectively.
- Each successive temporary object is initialized from the previous one as if by direct-initialization if X is a scalar type, otherwise by using an eligible trivial constructor.
- The function parameter or return object is initialized from the final temporary as if by direct-initialization if X is a scalar type, otherwise by using an eligible trivial constructor.
(In all cases, the eligible constructor is used even if that constructor is inaccessible or would not be selected by overload resolution to perform a copy or move of the object).
[Note 3:
This latitude is granted to allow objects to be passed to or returned from functions in registers.
— _end note_]
Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.
This is true even if that evaluation ends in throwing an exception.
Thevalue computations andside effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.
There are five contexts in which temporaries are destroyed at a different point than the end of the full-expression.
The first context is when a default constructor is called to initialize an element of an array with no corresponding initializer ([dcl.init]).
In either case, if the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.
The third context is when a reference binds to a temporary object.25
The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:
- a temporary materialization conversion ([conv.rval]),
- ( expression ), where expression is one of these expressions,
- subscripting ([expr.sub]) of an array operand, where that operand is one of these expressions,
- a class member access ([expr.ref]) using the . operator where the left operand is one of these expressions and the right operand designates a non-static data member of non-reference type,
- a pointer-to-member operation ([expr.mptr.oper]) using the .* operator where the left operand is one of these expressions and the right operand is a pointer to data member of non-reference type,
- a
- const_cast ([expr.const.cast]),
- static_cast ([expr.static.cast]),
- dynamic_cast ([expr.dynamic.cast]), or
- reinterpret_cast ([expr.reinterpret.cast])
converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,
- a conditional expression ([expr.cond]) that is a glvalue where the second or third operand is one of these expressions, or
- a comma expression ([expr.comma]) that is a glvalue where the right operand is one of these expressions.
[Example 2: template<typename T> using id = T;int i = 1;int&& a = id<int[3]>{1, 2, 3}[i]; const int& b = static_cast<const int&>(0); int&& c = cond ? id<int[3]>{1, 2, 3}[i] : static_cast<int&&>(0); — _end example_]
[Note 4:
An explicit type conversion ([expr.type.conv], [expr.cast]) is interpreted as a sequence of elementary casts, covered above.
[Example 3: const int& x = (const int&)1; — _end example_]
— _end note_]
[Note 5:
If a temporary object has a reference member initialized by another temporary object, lifetime extension applies recursively to such a member's initializer.
[Example 4: struct S { const int& m;};const S& s = S{1}; — _end example_]
— _end note_]
The exceptions to this lifetime rule are:
- A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.
- A temporary object bound to a reference element of an aggregate of class type initialized from a parenthesized expression-list ([dcl.init]) persists until the completion of the full-expression containing the expression-list.
- [Note 6:
This might introduce a dangling reference.
— end note_]
[_Example 5: struct S { int mi; const std::pair<int,int>& mp; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} }; — _end example_]
The fourth context is when a temporary object is created in the for-range-initializer of a range-based for statement.
If such a temporary object would otherwise be destroyed at the end of the for-range-initializer full-expression, the object persists for the lifetime of the reference initialized by the for-range-initializer.
The fifth context is when a temporary object is created in a structured binding declaration ([dcl.struct.bind]).
Any temporary objects introduced by the initializers for the variables with unique names are destroyed at the end of the structured binding declaration.
Let x and y each be either a temporary object whose lifetime is not extended, or a function parameter.
If the lifetimes of x and y end at the end of the same full-expression, andx is initialized before y, then the destruction of y is sequenced before that of x.
If the lifetime of two or more temporaries with lifetimes extending beyond the full-expressions in which they were created ends at the same point, these temporaries are destroyed at that point in the reverse order of the completion of their construction.
In addition, the destruction of such temporaries shall take into account the ordering of destruction of objects with static, thread, or automatic storage duration ([basic.stc.static], [basic.stc.thread], [basic.stc.auto]); that is, ifobj1is an object with the same storage duration as the temporary and created before the temporary is created the temporary shall be destroyed beforeobj1is destroyed; ifobj2is an object with the same storage duration as the temporary and created after the temporary is created the temporary shall be destroyed afterobj2is destroyed.
[Example 6: struct S { S(); S(int);friend S operator+(const S&, const S&);~S();}; S obj1;const S& cr = S(16)+S(23); S obj2;
The expressionS(16) + S(23)creates three temporaries: a first temporaryT1to hold the result of the expressionS(16), a second temporaryT2to hold the result of the expressionS(23), and a third temporaryT3to hold the result of the addition of these two expressions.
The temporaryT3is then bound to the referencecr.
It is unspecified whetherT1orT2is created first.
On an implementation whereT1is created beforeT2,T2shall be destroyed beforeT1.
The temporariesT1andT2are bound to the reference parameters ofoperator+; these temporaries are destroyed at the end of the full-expression containing the call tooperator+.
The temporaryT3bound to the referencecris destroyed at the end ofcr's lifetime, that is, at the end of the program.
In addition, the order in whichT3is destroyed takes into account the destruction order of other objects with static storage duration.
That is, becauseobj1is constructed beforeT3, andT3is constructed beforeobj2,obj2shall be destroyed beforeT3, andT3shall be destroyed beforeobj1.
— _end example_]