Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/language/definition"

From cppreference.com
< cpp‎ | language
(cwg 2300 (DR about lambdas vs ODR)., as a minimally-invasive and probably imprecise edit, this needs micro-examples if we are to make it any more standardese-ey (even the standard has some!), Also this DR snuck in a change from UB to NDR)
m (mark the bullet related to lambda-expression with since c++11/20)
Line 19: Line 19:
 
int S::i;                // defines S::i
 
int S::i;                // defines S::i
 
}}
 
}}
{{rev begin}}
+
{{rrev | since=c++17 |
{{rev | since=c++17 |
+
 
* {{mark deprecated}} Namespace scope declaration of a static data member that was defined within the class with the {{tt|{{rlp|constexpr}}}} specifier
 
* {{mark deprecated}} Namespace scope declaration of a static data member that was defined within the class with the {{tt|{{rlp|constexpr}}}} specifier
 
{{source|1=
 
{{source|1=
Line 29: Line 28:
 
}}
 
}}
 
}}
 
}}
{{rev end}}
 
 
* Declaration of a class name (by {{rlp|class#Forward declaration|forward declaration}} or by the use of the elaborated type specifier in another declaration)
 
* Declaration of a class name (by {{rlp|class#Forward declaration|forward declaration}} or by the use of the elaborated type specifier in another declaration)
 
{{source|
 
{{source|
Line 35: Line 33:
 
class Y f(class T p); // declares, but doesn't define Y and T (and also f and p)
 
class Y f(class T p); // declares, but doesn't define Y and T (and also f and p)
 
}}
 
}}
{{rev begin}}
+
{{rrev|since=c++11|
{{rev|since=c++11|
+
 
* An {{rlp|enum|opaque declaration}} of an enumeration
 
* An {{rlp|enum|opaque declaration}} of an enumeration
 
{{source|
 
{{source|
Line 42: Line 39:
 
}}
 
}}
 
}}
 
}}
{{rev end}}
 
 
* Declaration of a {{rlp|template parameters|template parameter}}
 
* Declaration of a {{rlp|template parameters|template parameter}}
 
{{source|
 
{{source|
Line 58: Line 54:
 
typedef S S2; // declares, but doesn't define S2 (S may be incomplete)
 
typedef S S2; // declares, but doesn't define S2 (S may be incomplete)
 
}}
 
}}
{{rev begin}}
+
{{rrev|since=c++11|
{{rev|since=c++11|
+
 
* An {{rlp|type alias|alias-declaration}}
 
* An {{rlp|type alias|alias-declaration}}
 
{{source|1=
 
{{source|1=
Line 65: Line 60:
 
}}
 
}}
 
}}
 
}}
{{rev end}}
 
 
* A {{rlp|using declaration|using-declaration}}
 
* A {{rlp|using declaration|using-declaration}}
 
{{source|1=
 
{{source|1=
Line 81: Line 75:
 
* An {{rlp|declarations|empty declaration}} (does not define any entities)
 
* An {{rlp|declarations|empty declaration}} (does not define any entities)
 
* A {{rlp|namespace#Using-directives|using-directive}} (does not define any entities)
 
* A {{rlp|namespace#Using-directives|using-directive}} (does not define any entities)
{{rev begin}}
+
{{rrev|since=c++11|
{{rev|since=c++11|
+
 
* An {{rlp|class_template#Class_template_instantiation|explicit instantiation declaration}} (an "extern template")
 
* An {{rlp|class_template#Class_template_instantiation|explicit instantiation declaration}} (an "extern template")
 
{{source|1=
 
{{source|1=
Line 88: Line 81:
 
}}
 
}}
 
}}
 
}}
{{rev end}}
 
 
* An {{rlp|template specialization|explicit specialization}} whose declaration is not a definition.
 
* An {{rlp|template specialization|explicit specialization}} whose declaration is not a definition.
 
{{source|1=
 
{{source|1=
Line 119: Line 111:
 
* name lookup from within each definition finds the same entities (after overload-resolution), except that
 
* name lookup from within each definition finds the same entities (after overload-resolution), except that
 
:* constants with internal or no linkage may refer to different objects as long as they are not ODR-used and have the same values in every definition
 
:* constants with internal or no linkage may refer to different objects as long as they are not ODR-used and have the same values in every definition
:* lambda-expressions that are not in a default argument or a default template argument are uniquely identified by the sequence of tokens used to define them
+
{{rrev|since=c++11|
 +
:* lambda-expressions that are not in a default argument{{rev inl|since=c++20| or a default template argument}} are uniquely identified by the sequence of tokens used to define them
 +
}}
 
* overloaded operators, including conversion, allocation, and deallocation functions refer to the same function from each definition (unless referring to one defined within the definition)
 
* overloaded operators, including conversion, allocation, and deallocation functions refer to the same function from each definition (unless referring to one defined within the definition)
 
* the language linkage is the same (e.g. the include file isn't inside an extern "C" block)
 
* the language linkage is the same (e.g. the include file isn't inside an extern "C" block)
Line 167: Line 161:
 
In the definitions above, ''potentially-evaluated'' means the expression is not an {{rlp|expressions#Unevaluated expressions|unevaluated operand}} (or its subexpression), such as the operand of {{rlp|sizeof}} and ''a set of potential results'' of an expression {{tt|e}} is a (possibly empty) set of id-expressions that appear within {{tt|e}}, combined as follows:
 
In the definitions above, ''potentially-evaluated'' means the expression is not an {{rlp|expressions#Unevaluated expressions|unevaluated operand}} (or its subexpression), such as the operand of {{rlp|sizeof}} and ''a set of potential results'' of an expression {{tt|e}} is a (possibly empty) set of id-expressions that appear within {{tt|e}}, combined as follows:
 
* If {{tt|e}} is an {{rlp|expressions|id-expression}}, the expression {{tt|e}} is its only potential result
 
* If {{tt|e}} is an {{rlp|expressions|id-expression}}, the expression {{tt|e}} is its only potential result
{{rev begin}}
+
{{rrev|since=c++17|
{{rev|since=c++17|
+
* If {{tt|e}} is an array subscript expression ({{c|e1[e2]}}) where one of the operands is an array, the potential results of that operand is included in the set
* If {{tt|e}} is an array subscript expression ({{c|e1[e2]}}) where one of the operands is an array, the potential results of that operand is included in the set}}
+
}}
{{rev end}}
+
 
* If {{tt|e}} is a class member access expression ({{c|e1.e2}} or {{c|e1->e2}}), the potential results of the object expression e1 is included in the set.
 
* If {{tt|e}} is a class member access expression ({{c|e1.e2}} or {{c|e1->e2}}), the potential results of the object expression e1 is included in the set.
 
* If {{tt|e}} is a pointer-to-member access expression ({{c|e1.*e2}} or {{c|e1->*e2}}) whose second operand is a constant expression, the potential results of the object expression e1 are included in the set
 
* If {{tt|e}} is a pointer-to-member access expression ({{c|e1.*e2}} or {{c|e1->*e2}}) whose second operand is a constant expression, the potential results of the object expression e1 are included in the set
Line 214: Line 207:
 
{{ref std end}}
 
{{ref std end}}
  
{{langlinks|es|zh}}
+
{{langlinks|es|ja|zh}}

Revision as of 21:02, 17 October 2019

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Definitions are declarations that fully define the entity introduced by the declaration. Every declaration is a definition, except for the following:

  • A function declaration without a function body
int f(int); // declares, but doesn't define f
extern const int a; // declares, but doesn't define a
extern const int b = 1; // defines b
struct S {
    int n;               // defines S::n
    static int i;        // declares, but doesn't define S::i
    inline static int x; // defines S::x
};                       // defines S
int S::i;                // defines S::i
  • (deprecated) Namespace scope declaration of a static data member that was defined within the class with the constexpr specifier
struct S {
    static constexpr int x = 42; // implicitly inline, defines S::x
};
constexpr int S::x; // declares S::x, not a redefinition
(since C++17)
  • Declaration of a class name (by forward declaration or by the use of the elaborated type specifier in another declaration)
struct S; // declares, but doesn't define S
class Y f(class T p); // declares, but doesn't define Y and T (and also f and p)
enum Color : int; // declares, but doesn't define Color
(since C++11)
template<typename T> // declares, but doesn't define T
  • A parameter declaration in a function declaration that isn't a definition
int f(int x); // declares, but doesn't define f and x
int f(int x) { // defines f and x
     return x+a;
}
typedef S S2; // declares, but doesn't define S2 (S may be incomplete)
using S2 = S; // declares, but doesn't define S2 (S may be incomplete)
(since C++11)
using N::d; // declares, but doesn't define d
(since C++17)
(since C++11)
extern template f<int, char>; // declares, but doesn't define f<int, char>
(since C++11)
template<> struct A<int>; // declares, but doesn't define A<int>

An asm declaration does not define any entities, but it is classified as a definition.

Where necessary, the compiler may implicitly define the default constructor, copy constructor, move constructor, copy assignment operator, move assignment operator, and the destructor.

If the definition of any object results in an object of incomplete type or abstract class type, the program is ill-formed.

One Definition Rule

Only one definition of any variable, function, class type, enumeration type, concept(since C++20) or template is allowed in any one translation unit (some of these may have multiple declarations, but only one definition is allowed).

One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined.

For an inline function or inline variable(since C++17), a definition is required in every translation unit where it is odr-used.

One and only one definition of a class is required to appear in any translation unit where the class is used in a way that requires it to be complete.

There can be more than one definition in a program of each of the following: class type, enumeration type, inline function, inline variable(since C++17), class template, non-static function template, static data member of a class template, member function of a class template, partial template specialization, concept,(since C++20) as long as all of the following is true:

  • each definition appears in a different translation unit
(since C++20)
  • each definition consists of the same sequence of tokens (typically, appears in the same header file)
  • name lookup from within each definition finds the same entities (after overload-resolution), except that
  • constants with internal or no linkage may refer to different objects as long as they are not ODR-used and have the same values in every definition
  • lambda-expressions that are not in a default argument or a default template argument(since C++20) are uniquely identified by the sequence of tokens used to define them
(since C++11)
  • overloaded operators, including conversion, allocation, and deallocation functions refer to the same function from each definition (unless referring to one defined within the definition)
  • the language linkage is the same (e.g. the include file isn't inside an extern "C" block)
  • the three rules above apply to every default argument used in each definition
  • if the definition is for a class with an implicitly-declared constructor, every translation unit where it is odr-used must call the same constructor for the base and members
  • if the definition is for a class with a defaulted three-way comparison, every translation unit where it is odr-used must call the same comparison operator for the base and members
(since C++20)
  • if the definition is for a template, then all these requirements apply to both names at the point of definition and dependent names at the point of instantiation

If all these requirements are satisfied, the program behaves as if there is only one definition in the entire program. Otherwise, the program is ill-formed, no diagnostic required.

Note: in C, there is no program-wide ODR for types, and even extern declarations of the same variable in different translation units may have different types as long as they are compatible. In C++, the source-code tokens used in declarations of the same type must be the same as described above: if one .cpp file defines struct S { int x; }; and the other .cpp file defines struct S { int y; };, the behavior of the program that links them together is undefined. This is usually resolved with unnamed namespaces.

ODR-use

Informally, an object is odr-used if its value is read (unless it is a compile time constant) or written, its address is taken, or a reference is bound to it; a reference is odr-used if it is used and its referent is not known at compile time; and a function is odr-used if a function call to it is made or its address is taken. If an object, a reference or a function is odr-used, its definition must exist somewhere in the program; a violation of that is usually a link-time error.

struct S {
    static const int x = 0; // static data member
    // a definition outside of class is required if it is odr-used
};
const int& f(const int& r);
 
int n = b ? (1, S::x) // S::x is not odr-used here
          : f(S::x);  // S::x is odr-used here: a definition is required

Formally,

1) a variable x in a potentially-evaluated expression ex is odr-used unless both of the following are true:
  • applying lvalue-to-rvalue conversion to x yields a constant expression that doesn't invoke non-trivial functions
  • either x is not an object (that is, x is a reference) or, if x is an object, it is one of the potential results of a larger expression e, where that larger expression is either a discarded-value expression or has the lvalue-to-rvalue conversion applied to it
struct S { static const int x = 1; }; // applying lvalue-to-rvalue conversion to S::x yields a constant expression
int f() { 
    S::x;        // discarded-value expression does not odr-use S::x
    return S::x; // expression where lvalue-to-rvalue conversion applies does not odr-use S::x
}
2) *this is odr-used if this appears as a potentially-evaluated expression (including the implicit this in a non-static member function call expression)
3) A structured binding is odr-used if it appears as a potentially-evaluated expression.
(since C++17)

In the definitions above, potentially-evaluated means the expression is not an unevaluated operand (or its subexpression), such as the operand of sizeof and a set of potential results of an expression e is a (possibly empty) set of id-expressions that appear within e, combined as follows:

  • If e is an id-expression, the expression e is its only potential result
  • If e is an array subscript expression (e1[e2]) where one of the operands is an array, the potential results of that operand is included in the set
(since C++17)
  • If e is a class member access expression (e1.e2 or e1->e2), the potential results of the object expression e1 is included in the set.
  • If e is a pointer-to-member access expression (e1.*e2 or e1->*e2) whose second operand is a constant expression, the potential results of the object expression e1 are included in the set
  • If e is an expression in parentheses ((e1)), the potential results of e1 are included in the set
  • If e is a glvalue conditional expression (e1?e2:e3, where e2 and e3 are glvalues), the union of the potential results of e2 and e3 are both included in the set.
  • If e is a comma expression (e1,e2), the potential results of e2 are in the set of potential results
  • Otherwise, the set is empty.
struct S {
  static const int a = 1;
  static const int b = 2;
};
int f(bool x) {
  return x ? S::a : S::b;
  // x is a part of the subexpression "x" (to the left of ?),
  // which applies lvalue-to-rvalue conversion, but applying that conversion to x
  // does not yield a constant expression, so x is odr-used
  // S::a and S::b are lvalues, and carry over as "potential results" to the result
  // of the glvalue conditional
  // That result is then subject to lvalue-to-rvalue conversion requested
  // to copy-initialize the return value, therefore S::a and S::b are not odr-used
}
4) Functions are ODR-used if
  • A function whose name appears as a potentially-evaluated expression (including named function, overloaded operator, user-defined conversion, user-defined placement forms of operator new, non-default initialization) is odr-used if it is selected by overload resolution, except when it is an unqualified pure virtual member function or a pointer-to-member to a pure virtual function(since C++17).
  • virtual member function is odr-used if it is not a pure virtual member function (addresses of virtual member functions are required to construct the vtable)
  • An allocation or deallocation function for a class is odr-used by a new expression appearing in a potentially-evaluated expression
  • A deallocation function for a class is odr-used by a delete expression appearing in a potentially-evaluated expression
  • A non-placement allocation or deallocation function for a class is odr-used by the definition of a constructor of that class.
  • A non-placement deallocation function for a class is odr-used by the definition of the destructor of that class, or by being selected by the lookup at the point of definition of a virtual destructor
  • An assignment operator in a class T that is a member or base of another class U is odr-used by an implicitly-defined copy-assignment or move-assignment functions of U.
  • A constructor (including default constructors) for a class is odr-used by the initialization that selects it.
  • A destructor for a class is odr-used if it is potentially invoked

In all cases, a constructor selected to copy or move an object is odr-used even if copy elision takes place.

References

  • C++11 standard (ISO/IEC 14882:2011):
  • 3.2 One definition rule [basic.def.odr]