Date:  2022-08-07
Project:  Programming Language C++
Reference:  ISO/IEC IS 14882:2020
Reply to:  Jens Maurer
 jens.maurer@gmx.net


C++ Standard Core Language Defect Reports and Accepted Issues, Revision 109


This document contains the C++ core language issues that have been categorized as Defect Reports by the Committee (PL22.16 + WG21) and other accepted issues, that is, issues with status "DR," "accepted," "DRWP," "WP," "CD1," "CD2," "CD3," "CD4," "CD5," "TC1," "C++11," "C++14," "C++17," and "C++20," along with their proposed resolutions. Issues with DR, accepted, DRWP, and WP status are NOT part of the International Standard for C++. They are provided for informational purposes only, as an indication of the intent of the Committee. They should not be considered definitive until or unless they appear in an approved Technical Corrigendum or revised International Standard for C++.

This document is part of a group of related documents that together describe the issues that have been raised regarding the C++ Standard. The other documents in the group are:

For more information, including a description of the meaning of the issue status codes and instructions on reporting new issues, please see the Active Issues List.

Section references in this document reflect the section numbering of document WG21 N4910.


Issues with "DR" Status


2540. Unspecified interpretation of numeric-escape-sequence

Section: 5.13.3  [lex.ccon]     Status: DR     Submitter: Richard Smith     Date: 2022-02-25

[Accepted at the July, 2022 meeting.]

Subclause 5.13.3 [lex.ccon] does not specify how the characters in an octal-escape-sequence or hexadecimal-escape-sequence are interpreted to obtain the integer value v that is used in bullet 3.2:

Proposed resolution (approved by CWG 2022-03-11):

  1. Change in 5.13.3 [lex.ccon] bullet 3.2 as follows:
    • A character-literal with a c-char-sequence consisting of a single numeric-escape-sequence that specifies an integer value v has a value as follows:
      • Let v be the integer value represented by the octal number comprising the sequence of octal-digits in an octal-escape-sequence or by the hexadecimal number comprising the sequence of hexadecimal-digits in a hexadecimal-escape-sequence.
      • If v does not exceed the range of representable values of the character-literal's type, then the value is v.
      • ...
  2. Change in 5.13.5 [lex.string] bullet 10.2 as follows:
    • Each numeric-escape-sequence (5.13.3 [lex.ccon]) that specifies an integer value v contributes a single code unit with a value as follows:
      • Let v be the integer value represented by the octal number comprising the sequence of octal-digits in an octal-escape-sequence or by the hexadecimal number comprising the sequence of hexadecimal-digits in a hexadecimal-escape-sequence.
      • If v does not exceed the range of representable values of the string-literal's array element type, then the value is v.
      • ...



2582. Differing member lookup from nested classes

Section: 6.5.2  [class.member.lookup]     Status: DR     Submitter: Jason Merrill     Date: 2022-05-02

[Accepted at the July, 2022 meeting.]

Consider:

  typedef int T;
  struct A {
   struct B {
    static T t;
   };
   typedef float T; // IFNDR?
  };

Subclause 6.5.2 [class.member.lookup] paragraph 6 specifies:

The result of the search is the declaration set of S(N, T). If it is an invalid set, the program is ill-formed. If it differs from the result of a search in T for N from immediately after the class-specifier of T, the program is ill-formed, no diagnostic required.

It is unclear whether the lookup of T inside A::B is subject to the "if it differs" rule, given that the class-specifier of A::B ends before introducing A::T.

Proposed resolution (approved by CWG 2022-05-06):

Change in 6.5.2 [class.member.lookup] paragraph 6 as follows:

If it differs from the result of a search in T for N from immediately after the class-specifier in a complete-class context of T, the program is ill-formed, no diagnostic required.



2594. Disallowing a global function template main

Section: 6.9.3.1  [basic.start.main]     Status: DR     Submitter: Jim X     Date: 2022-06-06

[Accepted at the July, 2022 meeting.]

Consider:

  template<class T>
  int main(T) {}

C++20 specified in 6.9.3.1 [basic.start.main] paragraph 2:

An implementation shall not predefine the main function. This function shall not be overloaded.

While it is unclear what "overloaded" means when multiple translation units are involved, it arguably disallowed function templates called main. This prohibition was removed with P1787R6 (Declarations and where to find them).

Proposed resolution (approved by CWG 2022-06-17):

Change in 6.9.3.1 [basic.start.main] paragraph 3 and add bullets as follows:

... A program that declares is ill-formed. The name main is not otherwise reserved.



2571. Evaluation order for subscripting

Section: 7.6.1.2  [expr.sub]     Status: DR     Submitter: Corentin Jabot     Date: 2022-04-21

[Accepted at the July, 2022 meeting.]

The specification about the relative sequencing of multiple parameters of the subscripting operator is missing. Also, issue 2507 adds support for default arguments for user-defined subscripting operators, but the sequencing of these is unspecified, too.

Suggested resolution: [SUPERSEDED]

Add a new paragraph 4 at the end of 7.6.1.2 [expr.sub]:

If the subscript operator invokes an operator function, the sequencing restrictions of the corresponding function call expression apply (12.4.5 [over.sub], 7.6.1.3 [expr.call]).

Notes from the 2022-05-20 CWG telecon:

A wording approach amending 12.2.2.3 [over.match.oper] paragraph 2 instead would be preferred.

Possible resolution (2022-05-21): [SUPERSEDED]

Change in 12.2.2.3 [over.match.oper] paragraph 2 as follows:

Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 17 (where @ denotes one of the operators covered in the specified subclause). However, except for the subscript operator (7.6.1.2 [expr.sub]), the operands are sequenced in the order prescribed for the built-in operator (7.6 [expr.compound]).

Notes from the 2022-06-03 CWG telecon:

Repeating the function call rules for the subscript operator in 7.6.1.2 [expr.sub] instead would be preferred, to avoid any impression of a special case.

Proposed resolution (2022-06-24, amended 2022-07-15, approved by CWG 2022-07-15):

Change in 7.6.1.2 [expr.sub] paragraph 1 as follows:

A subscript expression is a postfix expression followed by square brackets containing a possibly empty, comma-separated list of initializer-clauses which that constitute the arguments to the subscript operator. The postfix-expression and the initialization of the object parameter of any applicable subscript operator function is sequenced before each expression in the expression-list and also before any default argument. The initialization of a non-object parameter of a subscript operator function S (12.4.5 [over.sub]), including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other non-object parameter of S.



2534. Value category of pseudo-destructor expression

Section: 7.6.1.5  [expr.ref]     Status: DR     Submitter: Andrey Erokhin     Date: 2022-02-17

[Accepted at the July, 2022 meeting.]

Subclause 7.6.1.5 [expr.ref] paragraph 3 defines the value category of a pseudo-destructor class member access expression to be an lvalue:

Abbreviating postfix-expression.id-expression as E1.E2, E1 is called the object expression. If the object expression is of scalar type, E2 shall name the pseudo-destructor of that same type (ignoring cv-qualifications) and E1.E2 is an lvalue of type “function of () returning void”.
This is inconsistent with the analogous situation naming the destructor of a class. In that case, the class member access expression is a prvalue, not an lvalue, as specified in 7.6.1.5 [expr.ref] bullet 6.3 (see also issue 2458):
It also contradicts 7.2.1 [basic.lval] bullet 1.1:
A pseudo-destructor does not have an identity.

Proposed resolution (approved by CWG 2022-04-08):

Change 7.6.1.5 [expr.ref] paragraph 3 as follows:

If the object expression is of scalar type, E2 shall name the pseudo-destructor of that same type (ignoring cv-qualifications) and E1.E2 is an lvalue a prvalue of type “function of () returning void”.



2535. Type punning in class member access

Section: 7.6.1.5  [expr.ref]     Status: DR     Submitter: Andrey Erokhin     Date: 2022-02-17

[Accepted at the July, 2022 meeting.]

The initialization of j ought to have undefined behavior, but the standard does not explicitly say so:

  struct C { int m; };

  int i = 0;
  int j = reinterpret_cast<C&>(i).m; // the same as int j = i ?

A related case for pointer-to-member expressions is covered by 7.6.4 [expr.mptr.oper] paragraph 4:

If the dynamic type of E1 does not contain the member to which E2 refers, the behavior is undefined.

The invocation of non-static member functions is covered by 11.4.3 [class.mfct.non.static] paragraph 2:

If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.

Proposed resolution (approved by CWG 2022-06-17):

(updated according to 2022-05-20 and 2022-06-03 CWG guidance)

  1. Add a new paragraph after 7.6.1.5 [expr.ref] paragraph 7:

    If E2 is a non-static data member or a non-static member function, the program is ill-formed if the class of which E2 is directly a member is an ambiguous base (6.5.2 [class.member.lookup]) of the naming class (11.8.3 [class.access.base]) of E2. [Note: The program is also ill-formed if the naming class is an ambiguous base of the class type of the object expression; see 11.8.3 [class.access.base]. —end note -- end note]

    If E2 is a non-static member and the result of E1 is an object whose type is not similar (7.3.6 [conv.qual]) to the type of E1, the behavior is undefined. [ Example:

      struct A { int i; };
      struct B { int j; };
      struct D : A, B {};
      void f() {
        D d;
        static_cast<B&>(d).j;       // OK, object expression designates the B subobject of d
        reinterpret_cast<B&>(d).j;  // undefined behavior
      }
    
    -- end example ]

  2. Change in 7.6.4 [expr.mptr.oper] paragraph 4:

    If the dynamic type of E1 If the result of E1 is an object whose type is not similar to the type of E1, or whose most derived object does not contain the member to which E2 refers, the behavior is undefined. Otherwise, t The expression E1 is sequenced before the expression E2.
  3. Remove 11.4.3 [class.mfct.non.static] paragraph 2:

    If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.



2606. static_cast from "pointer to void" does not handle similar types

Section: 7.6.1.9  [expr.static.cast]     Status: DR     Submitter: Richard Smith     Date: 2022-06-28

[Accepted at the July, 2022 meeting.]

Consider:

  struct S {
    int a[5];
  } s;
  int (*p)[] = reinterpret_cast<int(*)[]>(&s);
  int n = (*p)[0];

This ought to have defined behavior: a pointer to s and a pointer to s.a are pointer-interconvertible, so you should be able to navigate between them this way. But the cast as shown does not work, because the type of the pointer-interconvertible object is int[5], not int[].

Proposed resolution (approved by CWG 2022-07-01):

Change in 7.6.1.9 [expr.static.cast] paragraph 13 as follows:

... Otherwise, if the original pointer value points to an object a, and there is an object b of type similar to T (ignoring cv-qualification) that is pointer-interconvertible (6.8.3 [basic.compound]) with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.



2585. Name lookup for coroutine allocation

Section: 9.5.4  [dcl.fct.def.coroutine]     Status: DR     Submitter: Xu Chuanqi     Date: 2022-05-12

[Accepted at the July, 2022 meeting.]

Consider:

  struct Allocator;

  struct resumable::promise_type {
    void* operator new(std::size_t sz, Allocator&);
    // ...
  };
  resumable foo() {
    co_return;
  }

Subclause 9.5.4 [dcl.fct.def.coroutine] paragraph 9 specifies:

... The allocation function's name is looked up by searching for it in the scope of the promise type. If no viable function is found (12.2.3 [over.match.viable]), overload resolution is performed again on a function call created by passing just the amount of space required as an argument of type std::size_t.

Is the example ill-formed because resumable::promise_type is not viable, or is the example well-formed because the global operator new can be used? There is implementation divergence.

See also LLVM issue 54881.

Proposed resolution (approved by CWG 2022-06-17):

(updated according to 2022-05-20, 2022-06-03, and 2022-06-17 CWG guidance)

Change in 9.5.4 [dcl.fct.def.coroutine] paragraph 9 as follows:

... The allocation function's name is looked up by searching for it in the scope of the promise type.



2597. Replaceable allocation and deallocation functions in the global module

Section: 10.1  [module.unit]     Status: DR     Submitter: Gabriel dos Reis     Date: 2022-06-17     Liaison: EWG

[Accepted at the July, 2022 meeting.]

Subclause 10.1 [module.unit] paragraph 7 implicitly attaches the replaceable global allocation or deallocation functions to the global module. Now that extern "C++" can be used to introduce declarations in the global module, even when in the purview of a named module, the provision seems superfluous.

Proposed resolution [SUPERSEDED]:

  1. Change in 6.7.5.5.1 [basic.stc.dynamic.general] paragraph 2 as follows:

    The library provides default definitions for the global allocation and deallocation functions. Some global allocation and deallocation functions are replaceable (17.6.3 [new.delete]). A C++ program shall provide at most one definition of a replaceable allocation or deallocation function. Any such function definition replaces the default version provided in the library (16.4.5.6 [replacement.functions]). The following allocation and deallocation functions (17.6 [support.dynamic]) are implicitly declared in global scope in each translation unit of a program and are attached to the global module (10.1 [module.unit]).
  2. Change in 10.1 [module.unit] bullet 7.2 as follows:

    • If the declaration is ...
    • Otherwise, if the declaration
      • is a replaceable global allocation or deallocation function (17.6.3.2 [new.delete.single], 17.6.3.3 [new.delete.array]), or
      • is a namespace-definition with external linkage, or
      • appears within a linkage-specification (9.11 [dcl.link]),
      it is attached to the global module.
    • Otherwise, ...

Additional notes (June, 2022):

Forwarded to EWG with paper issue 1273, by decision of the CWG chair.

Approved by EWG telecon 2022-07-07.

Proposed resolution (approved by CWG 2022-07-15):

  1. Change in 6.7.5.5.1 [basic.stc.dynamic.general] paragraph 2 as follows:

    The library provides default definitions for the global allocation and deallocation functions. Some global allocation and deallocation functions are replaceable (17.6.3 [new.delete]) ; these are attached to the global module 10.1 [module.unit]). A C++ program shall provide at most one definition of a replaceable allocation or deallocation function. Any such function definition replaces the default version provided in the library (16.4.5.6 [replacement.functions]). The following allocation and deallocation functions (17.6 [support.dynamic]) are implicitly declared in global scope in each translation unit of a program.
  2. Change in 10.1 [module.unit] bullet 7.2 as follows:

    • If the declaration is ...
    • Otherwise, if the declaration
      • is a replaceable global allocation or deallocation function (17.6.3.2 [new.delete.single], 17.6.3.3 [new.delete.array]), or
      • is a namespace-definition with external linkage, or
      • appears within a linkage-specification (9.11 [dcl.link]),
      it is attached to the global module.
    • Otherwise, ...



2405. Additional type-dependent expressions

Section: 13.8.3.3  [temp.dep.expr]     Status: DR     Submitter: Andrey Davydov     Date: 2018-08-20

[Accepted at the July, 2022 meeting.]

According to 13.8.3.3 [temp.dep.expr] paragraph 3,

...Expressions of the following forms are type-dependent only if the type specified by the type-id, simple-type-specifier or new-type-id is dependent, even if any subexpression is type-dependent:

This list is missing cases for:

Proposed resolution (approved by CWG 2022-06-17):

Change in 13.8.3.3 [temp.dep.expr] paragraph 3 as follows:

Expressions of the following forms are type-dependent only if the type specified by the type-id, simple-type-specifier, typename-specifier, or new-type-id is dependent, even if any subexpression is type-dependent:
simple-type-specifier ( expression-listopt )
simple-type-specifier braced-init-list
typename-specifier ( expression-listopt )
typename-specifier braced-init-list
...



2608. Omitting an empty template argument list

Section: 13.10.2  [temp.arg.explicit]     Status: DR     Submitter: Anoop Rana     Date: 2022-07-03

[Accepted at the July, 2022 meeting.]

Subclause 13.10.2 [temp.arg.explicit] paragraph 4 specifies:

Trailing template arguments that can be deduced (13.10.3 [temp.deduct]) or obtained from default template-arguments may be omitted from the list of explicit template-arguments.
[Note 1: A trailing template parameter pack (13.7.4 [temp.variadic]) not otherwise deduced will be deduced as an empty sequence of template arguments. —end note]
If all of the template arguments can be deduced, they may all be omitted; in this case, the empty template argument list <> itself may also be omitted.

The wording does not allow omitting the empty template argument list <> if all of the template arguments have been obtained from default template-arguments. For example:

  template<typename T = int>
  int f();

  int x = f();      // ill-formed per the wording
  int (*y)() = f;   // ditto

Proposed resolution (approved by CWG 2022-07-15):

Change in 13.10.2 [temp.arg.explicit] paragraph 4 as follows:

... If all of the template arguments can be deduced or obtained from default template-arguments, they may all be omitted; in this case, the empty template argument list <> itself may also be omitted.



2355. Deducing noexcept-specifiers

Section: 13.10.3.6  [temp.deduct.type]     Status: DR     Submitter: John Spicer     Date: 2017-09-06

[Accepted at the July, 2022 meeting.]

The list of deducible forms in 13.10.3.6 [temp.deduct.type] paragraph 8 does not include the ability to deduce the value of the constant in a noexcept-specifier, although implementations appear to allow it.

Notes from the April, 2018 teleconference:

Although this appears to be an obvious omission, CWG felt that EWG should weigh in on whether this capability should be supported or not.

EWG guidance (January, 2021):

Modify the Standard such that the value of a constant in a noexcept-specifier can be deduced. See vote.

Proposed resolution (June, 2022):

  1. Change 13.10.3.6 [temp.deduct.type] paragraph 3 as follows:

  2. A given type P can be composed from a number of other types, templates, and non-type values:

  3. Add the following to Example 3 in 13.10.3.6 [temp.deduct.type] paragraph 7:

  4. Here is an example where two template arguments are deduced from a single function parameter/argument pair...

    Here is an example where the exception specification of a function type is deduced:

      template <bool E> void f1(void (*)() noexcept(E));
      template<bool> struct A { };
      template<bool B> void f2(void (*)(A<B>) noexcept(B));
    
      void g1();
      void g2() noexcept;
      void g3(A<true>);
    
      void h() {
        f1(g1);    // OK: E is false
        f1(g2);    // OK: E is true
        f2(g3);    // error: B deduced as both true and false
      }
    

    Here is an example where a qualification conversion applies...

  5. Change 13.10.3.6 [temp.deduct.type] paragraph 8 as follows:

  6. A template type argument T, a template template argument TT, or a template non-type argument i can be deduced if P and A have one of the following forms:

    where (T) represents a parameter-type-list (9.3.4.6 [dcl.fct]) where at least one parameter type contains a T, and () represents a parameter-type-list where no parameter type contains a T.

    [Note: If a type matches such a form but contains no Ts, is, or TTs, deduction is not possible. —end note]

    Similarly, <T> represents template argument lists where at least one argument contains a T, <i> represents template argument lists where at least one argument contains an i and <> represents template argument lists where no argument contains a T or an i.

  7. Add the following as a new paragraph following 13.10.3.6 [temp.deduct.type] paragraph 14:

  8. The type of N in the type T[N] is std::size_t. [Example 9: ... —end example]

    The type of B in the noexcept-specifier noexcept(B) of a function type is bool.
    [Example:

      template<bool> struct A { };
      template<auto> struct B;
      template<auto X, void (*F)() noexcept(X)> struct B<F> {
        A<X> ax;
      };
      void f_nothrow() noexcept;
      B<f_nothrow> bn;   // OK: type of X deduced as bool
    

    end example]

  9. Change 13.10.3.6 [temp.deduct.type] paragraph 19 as follows:

  10. If P has a form that contains <i>, and if the type of i differs from the type of the corresponding template parameter of the template named by the enclosing simple-template-id, deduction fails. If P has a form that contains [i], and if the type of i is not an integral type, deduction fails.131 If P has a form that includes noexcept(i) and the type of i is not bool, deduction fails.
    [Example 12: ...
  11. Add the following as a new section preceding C.1.4 [diff.cpp20.library]:

  12. C.1.4 Clause 13: templates [diff.cpp20.temp]

    Affected subclause: 13.10.3.6 [temp.deduct.type]
    Change: Deducing template arguments from exception specifications.
    Rationale: Facilitate generic handling of throwing and non-throwing functions.
    Effect on original feature: Valid ISO C++20 code may be ill-formed in this revision of C++.

    [Example 1:

       template<bool> struct A { };
       template<bool B> void f(void (*)(A<B>) noexcept(B));
       void g(A<false>) noexcept;
       void h() {
         f(g);    // ill-formed; previously well-formed.
       }
    

    end example]






Issues with "accepted" Status


2586. Explicit object parameter for assignment and comparison

Section: 11.10.1  [class.compare.default]     Status: accepted     Submitter: Barry Revzin     Date: 2022-05-07     Liaison: EWG

[Accepted at the July, 2022 meeting.]

"Deducing this" allows to declare assignment and comparison operator functions as explicit object member functions.

However, such an assignment operator can never be a copy or move assignment operator, which means it always conflicts with the implicitly-defined one:

  struct C {
    C& operator=(this C&, C const&); // error: can't overload with the copy assignment operator
  };

Similarly, operator== or operator<=> can be declared with an explicit object parameter, but they cannot be defaulted:

  struct D {
    bool operator==(this D const&, D const&) = default; // error: not a kind of comparison that can be defaulted
  };

There seems to be no reason to disallow that, for people who prefer writing all of their members with explicit object parameters.

Suggested resolution:

  1. Change in 11.4.6 [class.copy.assign] paragraph 1 as follows:

    A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one non-object parameter of type X, X&, const X&, volatile X&, or const volatile X&.
  2. Change in 11.4.6 [class.copy.assign] paragraph 3 as follows:

    A user-declared move assignment operator X::operator= is a non-static non-template member function of class X with exactly one non-object parameter of type X&&, const X&&, volatile X&&, or const volatile X&&.
  3. Change in 11.10.1 [class.compare.default] paragraph 1 as follows:

    A defaulted comparison operator function (12.4.3 [over.binary]) for some class C shall be a non-template function that is
    • a non-static const non-volatile member of C having one parameter of type const C& and either no ref-qualifier or the ref-qualifier &, or or friend of C and
    • a friend of C having either has two parameters of type const C& or two parameters of type C , where the implicit object parameter (if any) is considered to be the first parameter..

Additional notes (May, 2022):

Forwarded to EWG with paper issue 1235, by decision of the CWG chair.

Approved by EWG telecon 2022-06-09 and EWG 2022-06 electronic poll.

See vote.

Additional notes (July, 2022):

The suggested resolution makes the following a copy assignment operator, suppressing the implicitly-declared one, which is surprising:

  struct B {
    B &operator =(this int, const B &); // copy assignment operator
  };

Proposed resolution (approved by CWG 2022-07-15):

  1. Change in 9.5.2 [dcl.fct.def.default] paragraph 2 as follows:

    The type T1 of an An explicitly defaulted special member function F F1 with type T1 is allowed to differ from the corresponding special member function F2 with type T2 it would have had if it were that would have been implicitly declared, as follows:
    • T1 and T2 may have differing ref-qualifiers;
    • if F2 has an implicit object parameter of type "reference to C", F1 may be an explicit object member function whose explicit object parameter is of type "reference to C";
    • T1 and T2 may have differing exception specifications; and
    • if T2 F2 has a non-object parameter of type const C&, the corresponding non-object parameter of T1 F1 may be of type C&.
    If T1 differs from T2 in any other a way other than as allowed by the preceding rules, then:
    • if F F1 is an assignment operator, and the return type of T1 differs from the return type of T2 or T1 F1's non-object parameter type is not a reference, the program is ill-formed;
    • otherwise, if F F1 is explicitly defaulted on its first declaration, it is defined as deleted;
    • otherwise, the program is ill-formed.
  2. Change in 11.4.6 [class.copy.assign] paragraph 1 as follows:

    A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one non-object parameter of type X, X&, const X&, volatile X&, or const volatile X&.
  3. Change in 11.4.6 [class.copy.assign] paragraph 3 as follows:

    A user-declared move assignment operator X::operator= is a non-static non-template member function of class X with exactly one non-object parameter of type X&&, const X&&, volatile X&&, or const volatile X&&.
  4. Change in 11.10.1 [class.compare.default] paragraph 1 as follows:

    A defaulted comparison operator function (12.4.3 [over.binary]) for some class C shall be a non-template function that is
    • a non-static const non-volatile member of C having one parameter of type const C& and either no ref-qualifier or the ref-qualifier &, or or friend of C and
    • a friend of C having either has two parameters of type const C& or two parameters of type C , where the implicit object parameter (if any) is considered to be the first parameter..



2507. Default arguments for operator[]

Section: 12.4.1  [over.oper.general]     Status: accepted     Submitter: Jens Maurer     Date: 2021-12-07

[Accepted at the July, 2022 meeting.]

The intent of paper P2128R6, which permitted multiple parameters in overloaded subscript operators and was adopted at the October, 2021 plenary, was that overloaded operator[] should allow parameters with default arguments. However, the adopted wording did not address the following restriction from 12.4.1 [over.oper.general] paragraph 10:

An operator function cannot have default arguments (9.3.4.7 [dcl.fct.default]), except where explicitly stated below.

Similar wording to that of operator() should be added for operator[].

Proposed resolution (December, 2021):

Change 12.4.5 [over.sub] paragraph 1 as follows:

A subscripting operator function is a function named operator[] that is a non-static member function with an arbitrary number of parameters. It may have default arguments. For an expression...

Approved by EWG 2022-04-14.

Approved by CWG 2022-04-22.






Issues with "DRWP" Status


536. Problems in the description of id-expressions

Section: _N4567_.5.1.1  [expr.prim.general]     Status: DRWP     Submitter: Mike Miller     Date: 13 October 2005

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

There are at least a couple of problems in the description of the various id-expressions in _N4567_.5.1.1 [expr.prim.general]:

  1. Paragraph 4 embodies an incorrect assumption about the syntax of qualified-ids:

    The operator :: followed by an identifier, a qualified-id, or an operator-function-id is a primary-expression.

    The problem here is that the :: is actually part of the syntax of qualified-id; consequently, “:: followed by... a qualified-id” could be something like “:: ::i,” which is ill-formed. Presumably this should say something like, “A qualified-id with no nested-name-specifier is a primary-expression.”

  2. More importantly, some kinds of id-expressions are not described by _N4567_.5.1.1 [expr.prim.general]. The structure of this section is that the result, type, and lvalue-ness are specified for each of the cases it covers:

    This treatment leaves unspecified all the non-identifier unqualified-ids (operator-function-id, conversion-function-id, and template-id), as well as (perhaps) “:: template-id” (it's not clear whether the “:: followed by a qualified-id” case is supposed to apply to template-ids or not). Note also that the proposed resolution of issue 301 slightly exacerbates this problem by removing the form of operator-function-id that contains a tmeplate-argument-list; as a result, references like “::operator+<X>” are no longer covered in _N4567_.5.1.1 [expr.prim.general].




1837. Use of this in friend and local class declarations

Section: _N4567_.5.1.1  [expr.prim.general]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-01-13

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The description of the use of this found in _N4567_.5.1.1 [expr.prim.general] paragraphs 3 and 4 allow it to appear in the declaration of a non-static member function following the optional cv-qualifier-seq and in the brace-or-equal-initializer of a non-static data member; all other uses are prohibited. These restrictions appear to allow questionable uses of this in several contexts. For example:

  template <typename T>
  struct Fish { static const bool value = true; };

  struct Other {
    int p();
    auto q() -> decltype(p()) *;
  };

  class Outer {
    // The following declares a member function of class Other.
    // Is this interpreted as Other* or Outer*?
    friend auto Other::q() -> decltype(this->p()) *;
    int g();
    int f() {
     extern void f(decltype(this->g()) *);
     struct Inner {
       // The following are all within the declaration of Outer::f().
       // Is this Outer* or Inner*?
       static_assert(Fish<decltype(this->g())>::value, "");
       enum { X = Fish<decltype(this->f())>::value };
       struct Inner2 : Fish<decltype(this->g())> { };
       friend void f(decltype(this->g()) *);
       friend auto Other::q() -> decltype(this->p()) *;
     };
     return 0;
    }
  };
  struct A {
   int f();
   bool b = [] {
    struct Local {
     static_assert(sizeof this->f() == sizeof(int), ""); // A or Local?
    };
   };
  };

There is implementation divergence on the treatment of these examples.




2165. Namespaces, declarative regions, and translation units

Section: _N4868_.6.4.1  [basic.scope.declarative]     Status: DRWP     Submitter: Richard Smith     Date: 2015-07-30

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The definition of “declarative region” given in _N4868_.6.4.1 [basic.scope.declarative] paragraph 1 is,

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.

According to 9.8 [basic.namespace] paragraph 1,

Unlike other declarative regions, the definition of a namespace can be split over several parts of one or more translation units.

This seems like a misuse of the term “declarative region”; in particular, a name x declared in namespace N in translation unit A cannot be used as an unqualified name in the part of namespace N in translation unit B unless it is also declared in B. See also issue 1884.




1291. Looking up a conversion-type-id

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: DRWP     Submitter: Daveed Vandevoorde     Date: 2011-04-10

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The Standard talks about looking up a conversion-type-id as if it were an identifier (_N4868_.6.5.6 [basic.lookup.classref] paragraph 7), but that is not exactly accurate. Presumably it should talk instead about looking up names (if any) appearing in the type-specifier-seq of the conversion-type-id.




1835. Dependent member lookup before <

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: DRWP     Submitter: Richard Smith     Date: 2014-01-17

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to _N4868_.6.5.6 [basic.lookup.classref] paragraph 1,

In a class member access expression (7.6.1.5 [expr.ref]), if the . or -> token is immediately followed by an identifier followed by a <, the identifier must be looked up to determine whether the < is the beginning of a template argument list (13.3 [temp.names]) or a less-than operator. The identifier is first looked up in the class of the object expression. If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class template.

Given

   template<typename T> T end(T);
   template<typename T>
   bool Foo(T it) {
     return it->end < it->end;
   }

since it is dependent and thus end cannot be looked up in the class of the object expression, it is looked up in the context of the postfix-expression. This lookup finds the function template, making the expression ill-formed.

One possibility might be to limit the lookup to the class of the object expression when the object expression is dependent.




1908. Dual destructor lookup and template-ids

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-03-31

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to _N4868_.6.5.6 [basic.lookup.classref] paragraph 3,

If the unqualified-id is ~type-name, the type-name is looked up in the context of the entire postfix-expression. If the type T of the object expression is of a class type C, the type-name is also looked up in the scope of class C. At least one of the lookups shall find a name that refers to (possibly cv-qualified) T.

This would apply to an example like

  namespace K {
    template <typename T, typename U = char> struct A { };
    A<short> *a;
  }

  template <typename T> using A = K::A<short, T>;

  int main() {
    K::a->~A<char>();
  }

Current implementations, however, only apply the dual lookup when the type-name is not a template-id. The specification should be changed to reflect current practice.




138. Friend declaration name lookup

Section: _N4868_.9.8.2.3  [namespace.memdef]     Status: DRWP     Submitter: Martin von Loewis     Date: 14 Jul 1999

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

_N4868_.9.8.2.3 [namespace.memdef] paragraph 3 says,

If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace... When looking for a prior declaration of a class or a function declared as a friend, scopes outside the innermost enclosing namespace scope are not considered.
It is not clear from this passage how to determine whether an entity is "first declared" in a friend declaration. One question is whether a using-declaration influences this determination. For instance:
    void foo();
    namespace A{
      using ::foo;
      class X{
	friend void foo();
      };
    }
Is the friend declaration a reference to ::foo or a different foo?

Part of the question involves determining the meaning of the word "synonym" in 9.9 [namespace.udecl] paragraph 1:

A using-declaration introduces a name into the declarative region in which the using-declaration appears. That name is a synonym for the name of some entity declared elsewhere.
Is "using ::foo;" the declaration of a function or not?

More generally, the question is how to describe the lookup of the name in a friend declaration.

John Spicer: When a declaration specifies an unqualified name, that name is declared, not looked up. There is a mechanism in which that declaration is linked to a prior declaration, but that mechanism is not, in my opinion, via normal name lookup. So, the friend always declares a member of the nearest namespace scope regardless of how that name may or may not already be declared there.

Mike Miller: 6.5.3 [basic.lookup.unqual] paragraph 7 says:

A name used in the definition of a class X outside of a member function body or nested class definition shall be declared in one of the following ways:... [Note: when looking for a prior declaration of a class or function introduced by a friend declaration, scopes outside of the innermost enclosing namespace scope are not considered.]
The presence of this note certainly implies that this paragraph describes the lookup of names in friend declarations.

John Spicer: It most certainly does not. If that section described the friend lookup it would yield the incorrect results for the friend declarations of f and g below. I don't know why that note is there, but it can't be taken to mean that that is how the friend lookup is done.

    void f(){}
    void g(){}
    class B {
        void g();
    };
    class A : public B {
        void f();
        friend void f(); // ::f not A::f
        friend void g(); // ::g not B::g
    };

Mike Miller: If so, the lookups for friend functions and classes behave differently. Consider the example in 6.5.6 [basic.lookup.elab] paragraph 3:

    struct Base {
        struct Data;         // OK: declares nested Data
        friend class Data;   // OK: nested Data is a friend
    };

If the friend declaration is not a reference to ::foo, there is a related but separate question: does the friend declaration introduce a conflicting (albeit "invisible") declaration into namespace A, or is it simply a reference to an as-yet undeclared (and, in this instance, undeclarable) A::foo? Another part of the example in 6.5.6 [basic.lookup.elab] paragraph 3 is related:

    struct Data {
        friend struct Glob;  // OK: Refers to (as yet) undeclared Glob
                             // at global scope.
    };

John Spicer: You can't refer to something that has not yet been declared. The friend is a declaration of Glob, it just happens to declare it in a such a way that its name cannot be used until it is redeclared.

(A somewhat similar question has been raised in connection with issue 36. Consider:

    namespace N {
        struct S { };
    }
    using N::S;
    struct S;          // legal?

According to 11.3 [class.name] paragraph 2,

A declaration consisting solely of class-key identifier ; is either a redeclaration of the name in the current scope or a forward declaration of the identifier as a class name.

Should the elaborated type declaration in this example be considered a redeclaration of N::S or an invalid forward declaration of a different class?)

(See also issues 95, 136, 139, 143, 165, and 166, as well as paper J16/00-0006 = WG21 N1229.)




1252. Overloading member function templates based on dependent return type

Section: _N4868_.12.2  [over.load]     Status: DRWP     Submitter: Nikolay Ivchenkov     Date: 2011-03-06

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The Standard does not allow overloading of member functions that differ only in their return type (cf enable_if).




1898. Use of “equivalent” in overload resolution

Section: _N4868_.12.3  [over.dcl]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-03-21

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The normative text of _N4868_.12.3 [over.dcl] relies on the term “equivalent,” for which it refers to _N4868_.12.2 [over.load], but the term appears there only in non-normative text. The resolution of this issue should be coordinated with that of issue 1668.




2494. Multiple definitions of non-odr-used entities

Section: 6.3  [basic.def.odr]     Status: DRWP     Submitter: Hubert Tong     Date: 2021-07-02

[Accepted at the February, 2022 meeting.]

According to 6.3 [basic.def.odr] paragraph 10,

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement (8.5.2 [stmt.if]); no diagnostic required.

This wording could be interpreted as allowing multiple definitions of non-inline variables and functions if they are not odr-used. That is presumably not the intent.

Notes from the August, 2021 teleconference:

CWG observed that there is a similar problem in paragraph 13. See also issue 1849.

Proposed resolution, December, 2021:

  1. Change 6.3 [basic.def.odr] paragraph 1 as follows:

  2. Each of the following is termed a definable item:

    No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, template, default argument for a parameter (for a function in a given scope), or default template argument definable item.

  3. Change 6.3 [basic.def.odr] paragraph 10 as follows:

  4. Every program shall contain exactly at least one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement (8.5.2 [stmt.if]); no diagnostic required. The definition...
  5. Change 6.3 [basic.def.odr] paragraph 13 as follows:

  6. There can be more than one definition of a

    in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements. For any definable item D with definitions in multiple translation units,

    the program is ill-formed; a diagnostic is required only if the definable item is attached to a named module and a prior definition is reachable at the point where a later definition occurs. Given such an entity D defined in more than one translation unit item, for all definitions of D, or, if D is an unnamed enumeration, for all definitions of D that are reachable at any given program point, the following requirements shall be satisfied...

  7. Delete 6.3 [basic.def.odr] paragraph 15:

  8. If these definitions do not satisfy these requirements, then the program is ill-formed; a diagnostic is required only if the entity is attached to a named module and a prior definition is reachable at the point where a later definition occurs.



554. Definition of “declarative region” and “scope”

Section: 6.4  [basic.scope]     Status: DRWP     Submitter: Gabriel Dos Reis     Date: 29 December 2005

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The various uses of the term “declarative region” throughout the Standard indicate that the term is intended to refer to the entire block, class, or namespace that contains a given declaration. For example, 6.4 [basic.scope] paragraph 2 says, in part:

[Example: in

    int j = 24;
    int main()
    {
        int i = j, j;
        j = 42;
    }

The declarative region of the first j includes the entire example... The declarative region of the second declaration of j (the j immediately before the semicolon) includes all the text between { and }...

However, the actual definition given for “declarative region” in 6.4 [basic.scope] paragraph 1 does not match this usage:

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.

Because (except in class scope) a name cannot be used before it is declared, this definition contradicts the statement in the example and many other uses of the term throughout the Standard. As it stands, this definition is identical to that of the scope of a name.

The term “scope” is also misused. The scope of a declaration is defined in 6.4 [basic.scope] paragraph 1 as the region in which the name being declared is valid. However, there is frequent use of the phrase “the scope of a class,” not referring to the region in which the class's name is valid but to the declarative region of the class body, and similarly for namespaces, functions, exception handlers, etc. There is even a mention of looking up a name “in the scope of the complete postfix-expression” (_N4868_.6.5.6 [basic.lookup.classref] paragraph 3), which is the exact inverse of the scope of a declaration.

This terminology needs a thorough review to make it logically consistent. (Perhaps a discussion of the scope of template parameters could also be added to section 6.4 [basic.scope] at the same time, as all other kinds of scopes are described there.)

Proposed resolution (November, 2006):

  1. Change 6.4 [basic.scope] paragraph 1 as follows:

  2. Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity a statement, block, function declarator, function-definition, class, handler, template-declaration, template-parameter-list of a template template-parameter, or namespace. In general, each particular name is valid may be used as an unqualified name to refer to the entity of its declaration or to the label only within some possibly discontiguous portion of program text called its scope. To determine the scope of a declaration...
  3. Change 6.4 [basic.scope] paragraph 3 as follows:

  4. The names declared by a declaration are introduced into the scope in which the declaration occurs declarative region that directly encloses the declaration, except that declaration-statements, function parameter names in the declarator of a function-definition, exception-declarations (6.4.3 [basic.scope.block]), the presence of a friend specifier (11.8.4 [class.friend]), certain uses of the elaborated-type-specifier (9.2.9.4 [dcl.type.elab]), and using-directives (9.8.4 [namespace.udir]) alter this general behavior.
  5. Change 6.4.3 [basic.scope.block] paragraphs 1-3 and add a new paragraph 4 before the existing paragraph 4 as follows:

  6. A name declared in a block (8.4 [stmt.block]) is local to that block. Its potential scope begins at its point of declaration (6.4.2 [basic.scope.pdecl]) and ends at the end of its declarative region. The declarative region of a name declared in a declaration-statement is the directly enclosing block (8.4 [stmt.block]). Such a name is local to the block.

    The potential scope declarative region of a function parameter name (including one appearing in the declarator of a function-definition or in a lambda-parameter-declaration-clause) or of a function-local predefined variable in a function definition (9.5 [dcl.fct.def]) begins at its point of declaration. If the function has a function-try-block the potential scope of a parameter or of a function-local predefined variable ends at the end of the last associated handler, otherwise it ends at the end of the outermost block of the function definition. A parameter name is the entire function definition or lambda-expression. Such a name is local to the function definition and shall not be redeclared in the any outermost block of the function definition nor in the outermost block of any handler associated with a function-try-block function-body (including handlers of a function-try-block) or lambda-expression.

    The name in a catch exception-declaration The declarative region of a name declared in an exception-declaration is its entire handler. Such a name is local to the handler and shall not be redeclared in the outermost block of the handler.

    The potential scope of any local name begins at its point of declaration (6.4.2 [basic.scope.pdecl]) and ends at the end of its declarative region.

  7. Change _N4868_.6.4.5 [basic.funscope] as indicated:

  8. Labels (8.2 [stmt.label]) have function scope and may be used anywhere in the function in which they are declared except in members of local classes (11.6 [class.local]) of that function. Only labels have function scope.
  9. Change 8.8 [stmt.dcl] paragraph 1 as follows:

  10. A declaration statement introduces one or more new identifiers names into a block; it has the form

    [Note: If an identifier a name introduced by a declaration was previously declared in an outer block, the outer declaration is hidden for the remainder of the block, after which it resumes its force (_N4868_.6.4.10 [basic.scope.hiding]). end note]

[Drafting notes: This resolution deals almost exclusively with the unclear definition of “declarative region.” I've left the ambiguous use of “scope” alone for now. However sections 3.3.x all have headings reading “xxx scope,” but they don't mean the scope of a declaration but the different kinds of declarative regions and their effects on the scope of declarations contained therein. To me, it looks like most of 3.4 should refer to “declarative region” and not to “scope.”

The change to 6.7 fixes an “identifier” misuse (e.g., extern T operator+(T,T); at block scope introduces a name but not an identifier) and removes normative redundancy.]

Notes from the October, 2015 meeting:

This issue has been returned to "drafting" status to be reconciled with changes to the underlying existing text.




2009. Unclear specification of class scope

Section: 6.4.6  [basic.scope.class]     Status: DRWP     Submitter: Richard Smith     Date: 2014-09-23

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Point 2 of the rules of class scope in 6.4.6 [basic.scope.class] paragraph 1 says,

A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

It is not clear that this provision does not apply to names appearing in function bodies, default arguments, exception-specifications, and brace-or-equal-initializers. It is also not clear what it means to “re-evaluate” a name.

One possible approach to this problem would be to say that all names declared in a class are visible throughout the class and simply make it ill-formed to refer to a name that has not been declared yet in the contexts in which that is problematic, such as types and template arguments.

In addition, the fourth point says,

A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function's class.

This rule is unneeded, as it simply restates the normal hiding rule in _N4868_.6.4.1 [basic.scope.declarative] paragraph 1:

The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name. In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration



2331. Redundancy in description of class scope

Section: 6.4.6  [basic.scope.class]     Status: DRWP     Submitter: Thomas Köppe     Date: 2016-12-07

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

[Accepted as a DR at the February, 2019 meeting.]

The first four paragraphs of 6.4.6 [basic.scope.class] are somewhat redundant. In particular:

This is editorial issue 1169.

Proposed resolution (November, 2018):

In 6.4.6 [basic.scope.class], delete paragraph 1, move paragraph 4 to the beginning, and make paragraph 3 a note:

The potential scope of a name declared in a class consists not only of the declarative region following the name's point of declaration, but also of all complete-class contexts (11.4 [class.mem]) of that class.

The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, and member function definitions, including the member function body and any portion of the declarator part of such definitions which follows the declarator-id, including a parameter-declaration-clause and any default arguments (9.3.4.7 [dcl.fct.default])).

A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

[Note: A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function's class (_N4868_.6.4.10 [basic.scope.hiding]). end note]

The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, and member function definitions, including the member function body and any portion of the declarator part of such definitions which follows the declarator-id, including a parameter-declaration-clause and any default arguments (9.3.4.7 [dcl.fct.default])).

Additional note, March, 2019:

The resolution emoves the rule that a class member name can be found by unqualified lookup prior to its point of definition in complete-class contexts, at least in non-defining member declarations:

  struct X {
    void f(int n = k); // was valid, now ill-formed
    static int k;
  };

Relatedly, the "member definitions" rule (formerly p4, now p2) that was used to justify the removal of p1 is wrong (both before and after that change):

  struct A {
    void f(B b) {} // was always (incorrectly) valid
    struct B {};
  };

For these reasons, this issue has been returned to "drafting" status.




191. Name lookup does not handle complex nesting

Section: 6.5.3  [basic.lookup.unqual]     Status: DRWP     Submitter: Alan Nash     Date: 29 Dec 1999

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The current description of unqualified name lookup in 6.5.3 [basic.lookup.unqual] paragraph 8 does not correctly handle complex cases of nesting. The Standard currently reads,

A name used in the definition of a function that is a member function (9.3) of a class X shall be declared in one of the following ways:
In particular, this formulation does not handle the following example:
    struct outer {
        static int i;
        struct inner {
            void f() {
                struct local {
                    void g() {
                        i = 5;
                    }
                };
            }
        };
    };
Here the reference to i is from a member function of a local class of a member function of a nested class. Nothing in the rules allows outer::i to be found, although intuitively it should be found.

A more comprehensive formulation is needed that allows traversal of any combination of blocks, local classes, and nested classes. Similarly, the final bullet needs to be augmented so that a function need not be a (direct) member of a namespace to allow searching that namespace when the reference is from a member function of a class local to that function. That is, the current rules do not allow the following example:

    int j;    // global namespace
    struct S {
        void f() {
            struct local2 {
                void g() {
                    j = 5;
                }
            };
        }
    };



405. Unqualified function name lookup

Section: 6.5.3  [basic.lookup.unqual]     Status: DRWP     Submitter: William M. Miller     Date: 14 Apr 2003

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

There seems to be some confusion in the Standard regarding the relationship between 6.5.3 [basic.lookup.unqual] (Unqualified name lookup) and 6.5.4 [basic.lookup.argdep] (Argument-dependent lookup). For example, 6.5.3 [basic.lookup.unqual] paragraph 3 says,

The lookup for an unqualified name used as the postfix-expression of a function call is described in 6.5.4 [basic.lookup.argdep].

In other words, nothing in 6.5.3 [basic.lookup.unqual] applies to function names; the entire lookup is described in 6.5.4 [basic.lookup.argdep].

6.5.4 [basic.lookup.argdep] does not appear to share this view of its responsibility. The closest it comes is in 6.5.4 [basic.lookup.argdep] paragraph 2a:

...the set of declarations found by the lookup of the function name is the union of the set of declarations found using ordinary unqualified lookup and the set of declarations found in the namespaces and classes associated with the argument types.

Presumably, "ordinary unqualified lookup" is a reference to the processing described in 6.5.3 [basic.lookup.unqual], but, as noted above, 6.5.3 [basic.lookup.unqual] explicitly precludes applying that processing to function names. The details of "ordinary unqualified lookup" of function names are not described anywhere.

The other clauses that reference 6.5.4 [basic.lookup.argdep], clauses Clause 12 [over] and Clause 13 [temp], are split over the question of the relationship between 6.5.3 [basic.lookup.unqual] and 6.5.4 [basic.lookup.argdep]. 12.2.2.2.2 [over.call.func] paragraph 3, for instance, says

The name is looked up in the context of the function call following the normal rules for name lookup in function calls (6.5.4 [basic.lookup.argdep]).

I.e., this reference assumes that 6.5.4 [basic.lookup.argdep] is self-contained. The same is true of 12.2.2.3 [over.match.oper] paragraph 3, second bullet:

The set of non-member candidates is the result of the unqualified lookup of operator@ in the context of the expression according to the usual rules for name lookup in unqualified function calls (6.5.4 [basic.lookup.argdep]), except that all member functions are ignored.

On the other hand, however, 13.8.4.2 [temp.dep.candidate] paragraph 1 explicitly assumes that 6.5.3 [basic.lookup.unqual] and 6.5.4 [basic.lookup.argdep] are both involved in function name lookup and do different things:

For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (6.5.3 [basic.lookup.unqual], 6.5.4 [basic.lookup.argdep]) except that:

Suggested resolution:

Change 6.5.3 [basic.lookup.unqual] paragraph 1 from

...name lookup ends as soon as a declaration is found for the name.

to

...name lookup ends with the first scope containing one or more declarations of the name.

Change the first sentence of 6.5.3 [basic.lookup.unqual] paragraph 3 from

The lookup for an unqualified name used as the postfix-expression of a function call is described in 6.5.4 [basic.lookup.argdep].

to

An unqualified name used as the postfix-expression of a function call is looked up as described below. In addition, argument-dependent lookup (6.5.4 [basic.lookup.argdep]) is performed on this name to complete the resulting set of declarations.



1200. Lookup rules for template parameters

Section: 6.5.3  [basic.lookup.unqual]     Status: DRWP     Submitter: Johannes Schaub     Date: 2010-09-18

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Although 6.4.8 [basic.scope.temp] now describes the scope of a template parameter, the description of unqualified name lookup in 6.5.3 [basic.lookup.unqual] do not cover uses of template parameter names. The note in 6.5.3 [basic.lookup.unqual] paragraph 16 says,

the rules for name lookup in template definitions are described in 13.8 [temp.res].

but the rules there cover dependent and non-dependent names, not template parameters themselves.




2370. friend declarations of namespace-scope functions

Section: 6.5.3  [basic.lookup.unqual]     Status: DRWP     Submitter: Andrew Marino     Date: 2017-12-04

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Issue 1906 discussed unqualified lookup in friend declarations of class member functions, and CWG decided to reaffirm the existing specification without change. However, there is a similar issue regarding friend declarations of namespace-scope functions. According to 6.5.3 [basic.lookup.unqual] paragraph 9,

Name lookup for a name used in the definition of a friend function (11.8.4 [class.friend]) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions. If the friend function is not defined in the class granting friendship, name lookup in the friend function definition shall proceed as described for lookup in namespace member function definitions.

In particular, “as described for lookup in member function definitions” does not consider names declared in the namespace of the friend function, and non-defining friend declarations of namespace-scope functions are not described at all. There is implementation divergence on these points. For example:

  namespace N {
    typedef int type;
    void f(type);
    void g(type);
    void h(type);
  }
  class C {
    typedef N::type N_type;
    friend void N::f(type) { }  // Ill-formed: cannot define namespace friend
    friend void N::g(type);     // Unclear whether type is found or not
    friend void N::h(N_type);   // Unclear whether N_type is found or not
  };

Notes from the November, 2018 meeting:

CWG agreed that the lookup for functions in namespaces should be similar to that for class member functions.




1771. Restricted lookup in nested-name-specifier

Section: 6.5.5  [basic.lookup.qual]     Status: DRWP     Submitter: Canada     Date: 2013-09-24

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

N3690 comment CA 21

Consider the following example:

  template <typename T> struct B { };
  namespace N {
    namespace L {
      template <int> void A();
    }
    namespace M {
      template <int> struct A { typedef int y; };
    }
    using namespace L;
    using namespace M;
  }
  B<N::/*template */A<0>::y> (x);

Which A is referenced in the last line? According to 6.5.5 [basic.lookup.qual] paragraph 1,

If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types.

It is not clear whether this applies to the example or not, and the interpretation of the < token depends on the result of the lookup.

Notes from the September, 2013 meeting:

The restricted lookup mentioned in 6.5.5 [basic.lookup.qual] paragraph 1 is based on a one-token lookahead; because the next token following A in the example is not ::, the restricted lookup does not apply, and the result is ambiguous. Uncommenting the template keyword in the example does not affect the lookup.




1828. nested-name-specifier ambiguity

Section: 6.5.5  [basic.lookup.qual]     Status: DRWP     Submitter: Richard Smith     Date: 2014-01-08

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Issue 125 concerned an example like

  friend A::B::C();

which might be parsed as either

  friend A (::B::C)();

or

  friend A::B (::C)();

Its resolution attempted to make such constructs unambiguously ill-formed by allowing any identifier, not just namespaces and types, to appear in a nested-name-specifier, apparently on the assumption that C in this case would become part of an ill-formed nested-name-specifier instead of being taken as the unqualified-id in a qualified-id. Unfortunately, the current specification does not implement that intent, leaving both parses as valid possibilities.

A different approach might be to adjust the specification of the lookup of names appearing in nested-name-specifiers from

If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types. If the name found does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed.

to

Lookup of an identifier followed by a :: scope resolution operator considers only namespaces, types, and templates whose specializations are types. If an identifer, template-id, or decltype-specifier is followed by a :: scope resolution operator, the name shall designate a namespace, class, enumeration, or dependent type, and shall form part of a nested-name-specifier.

This approach would also remove the need for deferred lookup for template-ids and thus resolve issue 1771.




562. qualified-ids in non-expression contexts

Section: 6.5.5.2  [class.qual]     Status: DRWP     Submitter: Mike Miller     Date: 6 April 2006

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Both 6.5.5.2 [class.qual] and 6.5.5.3 [namespace.qual] specify that some lookups are to be performed “in the context of the entire postfix-expression,” ignoring the fact that qualified-ids can appear outside of expressions.

It was suggested in document J16/05-0156 = WG21 N1896 that these uses be changed to “the context in which the qualified-id occurs,” but it isn't clear that this formulation adequately covers all the places a qualified-id can occur.




2070. using-declaration with dependent nested-name-specifier

Section: 6.5.5.2  [class.qual]     Status: DRWP     Submitter: Richard Smith     Date: 2015-01-15

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

It makes no sense for a user to write a class template that contains a using-declaration that is sometimes an inheriting constructor declaration and sometimes pulls in a named value from a base class; These are sufficiently different things that we're doing them a disservice by conflating them. We're also doing a disservice to all readers of the code, by allowing an inheriting constructor to be written using a syntax that does not look like one.

In an inheriting constructor using-declaration, the nested-name-specifier and the unqualified-id should be required to be the same identifier.

Notes from the May, 2015 meeting:

The consensus of CWG was that the same name should be required when the nested-name-specifier is dependent and in the using-declaration case but should be allowed to be different in all other cases. See also issues 156 and 399.




279. Correspondence of "names for linkage purposes"

Section: 6.6  [basic.link]     Status: DRWP     Submitter: Daveed Vandevoorde     Date: 4 Apr 2001

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The standard says that an unnamed class or enum definition can be given a "name for linkage purposes" through a typedef. E.g.,

    typedef enum {} E;
    extern E *p;

can appear in multiple translation units.

How about the following combination?

    // Translation unit 1:
    struct S;
    extern S *q;

    // Translation unit 2:
    typedef struct {} S;
    extern S *q;

Is this valid C++?

Also, if the answer is "yes", consider the following slight variant:

    // Translation unit 1:
    struct S {};  // <<-- class has definition
    extern S *q;

    // Translation unit 2:
    typedef struct {} S;
    extern S *q;

Is this a violation of the ODR because two definitions of type S consist of differing token sequences?




338. Enumerator name with linkage used as class name in other translation unit

Section: 6.6  [basic.link]     Status: DRWP     Submitter: Daveed Vandevoorde     Date: 26 Feb 2002

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The following declarations are allowed within a translation unit:

  struct S;
  enum { S };

However, 6.6 [basic.link] paragraph 9 seems to say these two declarations cannot appear in two different translation units. That also would mean that the inclusion of a header containing the above in two different translation units is not valid C++.

I suspect this is an oversight and that users should be allowed to have the declarations above appear in different translation units. (It is a fairly common thing to do, I think.)

Mike Miller: I think you meant "enum E { S };" -- enumerators only have external linkage if the enumeration does (6.6 [basic.link] paragraph 4) , and 6.6 [basic.link] paragraph 9 only applies to entities with external linkage.

I don't remember why enumerators were given linkage; I don't think it's necessary for mangling non-type template arguments. In any event, I can't think why cross-TU name collisions between enumerators and other entities would cause a problem, so I guess a change here would be okay. I can think of three changes that would have that effect:

  1. Saying that enumerators do not have linkage.
  2. Removing enumerators from the list of entities in the first sentence of 6.6 [basic.link] paragraph 9.
  3. Saying that it's okay for an enumerator in one TU to have the same name as a class type in another TU only if the enumerator hides that same class type in both TUs (the example you gave).

Daveed Vandevoorde: I don't think any of these are sufficient in the sense that the problem isn't limited to enumerators. E.g.:

  struct X;
  extern void X();
shouldn't create cross-TU collisions either.

Mike Miller: So you're saying that cross-TU collisions should only be prohibited if both names denote entities of the same kind (both functions, both objects, both types, etc.), or if they are both references (regardless of what they refer to, presumably)?

Daveed Vandevoorde: Not exactly. Instead, I'm saying that if two entities (with external linkage) can coexist when they're both declared in the same translation unit (TU), then they should also be allowed to coexist when they're declared in two different translation units.

For example:

  int i;
  void i();  // Error
This is an error within a TU, so I don't see a reason to make it valid across TUs.

However, "tag names" (class/struct/union/enum) can sometimes coexist with identically named entities (variables, functions & enumerators, but not namespaces, templates or type names).




1839. Lookup of block-scope extern declarations

Section: 6.6  [basic.link]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-01-18

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 6.6 [basic.link] paragraph 6,

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed.

It is not clear how declarations that are in the lexical scope of the block-scope declaration but not members of the nearest enclosing namespace (see 9.8.2 [namespace.def] paragraph 6) should be treated. (For example, the definition of the function in which the block extern appears might be defined in an enclosing namespace, with a visible declaration of the name in that namespace, or it might be a member function of a class containing a member function of the name being declared.) Should such declarations be produce an error or should the lexically-nearer declaration simply be ignored? There is implementation divergence on this point.

Proposed resolution, April, 2019:

  1. Change 6.6 [basic.link] paragraph 8 as follows:

  2. The name of a A function declared in block scope and the name of or a variable declared by a block scope extern declaration have is a member of the innermost enclosing namespace and its name has linkage. If such a declaration is attached to a named module, the program is ill-formed. If there is a visible prior declaration of an entity with linkage, ignoring entities declared outside the innermost enclosing namespace scope that name in that namespace, such that the block scope declaration would be a (possibly ill-formed) redeclaration if the two declarations appeared in the same declarative region, the block scope declaration declares that same entity and its name receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external the linkage of the innermost enclosing namespace. If, within a translation unit, the same entity is declared with both internal and external linkage, the program is ill-formed. [Example:

      static void f();
      extern "C" void h();
      static int i = 0;    // #1
      void g() {
        extern void f();   // internal linkage
        extern void h();   // C language linkage
        extern void k();   // ::k, external linkage
        int i;             // #2: i has no linkage
        {
          extern void f(); // internal linkage
          extern int i;    // #3: external internal linkage, ill-formed
        }
      }
    

    Without the declaration at line #2, the declaration at line #3 would link with the declaration at line #1. Because the declaration with internal linkage is hidden, however, #3 is given external linkage, making the program ill-formed. Even though the declaration at line #2 hides the declaration at line #1, the declaration at line #3 still redeclares #1 and receives internal linkage.end example]

  3. Change 6.6 [basic.link] paragraph 9 as follows:

  4. When a A block scope declaration of an entity with linkage is not found to refer to some other declaration, then that entity is a member of the innermost enclosing namespace. However such a declaration does not introduce by itself make the member name visible to any form of name lookup in its namespace scope or eligible for declaration by qualified-id. [Example:

      namespace X {
        void p() {
          q();                   // error: q not yet declared
          extern void q();       // q is a member of namespace X
          extern void r();       // r is a member of namespace X
        }
    
        void middle() {
          q();                   // error: q not yet declared visible to name lookup
        }
    
        void q() { /* ... */ }   // definition of X::q
      }
    
      void q() { /* ... */ }     // some other, unrelated q
      void X::r() { /* ... */ }  // error: r cannot be declared by qualified-id
    

    end example]

Additional note, July, 2019:

The proposed resolution removes the sentence from the existing text reading:

If, within a translation unit, the same entity is declared with both internal and external linkage, the program is ill-formed.

Such a sitution can still arise, however:

   void f() {
     void g(); // external linkage
   }
   static void g(); // internal linkage

The remaining wording dealing with linkage agreement, 9.2.2 [dcl.stc] paragraph 6,

The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same variable name or the same overloading of a function name shall imply the same linkage.

does not apply to this example because the declarations are not within the same scope.

The issue has been returned to "review" status to allow consideration of how best to address this problem.




1884. Unclear requirements for same-named external-linkage entities

Section: 6.6  [basic.link]     Status: DRWP     Submitter: Richard Smith     Date: 2014-02-27

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 6.6 [basic.link] paragraph 9,

Two names that are the same (6.1 [basic.pre]) and that are declared in different scopes shall denote the same variable, function, type, enumerator, template or namespace if

This is not as clear as it should be. The intent is that this rule prevents declaring a name with extenal linkage to be, for instance, a type in one translation unit and a namespace in a different translation unit. It has instead been read as begging the question of what it means for two entities to be the same. The wording should be tweaked to make the intention clear. Among other things, it should be clarified that "declared in" refers to the namespace of which the name is a member, not the lexical scope in which the declaration appears (which affects friend declarations, block-scope extern declarations, and elaborated-type-specifiers).

There is a similar restriction in _N4868_.6.4.1 [basic.scope.declarative] paragraph 4 dealing with declarations within a single declarative region, while 6.6 [basic.link] paragraph 9 deals with names that are associated via linkage. The relationship between these complementary requirements may need to be clarified as well.

See also issue 2165.

Additional note, March, 2019:

6.6 [basic.link] paragraph 11 concludes by saying,

A violation of this rule on type identity does not require a diagnostic.

Presumably a diagnostic should be required if the differing types appear within a single translation unit.




2058. More errors from internal-linkage namespaces

Section: 6.6  [basic.link]     Status: DRWP     Submitter: Richard Smith     Date: 2014-12-15

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Issue 1603 dealt with omissions in the application of the change to give unnamed namespaces internal linkage, but its resolution overlooked a couple of items. According to 6.6 [basic.link] paragraph 6,

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.

The last sentence should say, “...receives the linkage of the innermost enclosing namespace.”

Also, 6.6 [basic.link] paragraph 8 says,

A type without linkage shall not be used as the type of a variable or function with external linkage unless

This bullet cannot occur, since a function or variable declared within an unnamed namespace cannot have external linkage.




2470. Multiple array objects providing storage for one object

Section: 6.7.2  [intro.object]     Status: DRWP     Submitter: Andrey Erokhin     Date: 2021-01-29

According to 6.7.2 [intro.object] paragraph 3,

If a complete object is created (7.6.2.8 [expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std::byte” (17.2.1 [cstddef.syn]), that array provides storage for the created object if:

The intent of the third bullet is to select a unique array object among those satisfying the first two bullets. However, it is possible to have multiple array objects of the same size satisfying the first two bullets. For example:

  unsigned char buffer[8];
  struct OhNo { std::byte data[8]; };
  static_assert(sizeof(OhNo) == 8 && sizeof(int) == 4);
  OhNo *p = new (buffer) OhNo;   // buffer provides storage for OhNo
  int *q = new (p->data) int;    // who provides storage for this?
  int *r = new (buffer + 4) int; // who provides storage for this?

Suggested resolution:

Change 6.7.2 [intro.object] bullet 3.3 as follows:

Proposed resolution (February, 2021):

Change 6.7.2 [intro.object] bullet 3.3 as follows:




2448. Cv-qualification of arithmetic types and deprecation of volatile

Section: 6.8.2  [basic.fundamental]     Status: DRWP     Submitter: Alisdair Meredith     Date: 2020-03-23

[Accepted as a DR at the June, 2021 meeting.]

According to the definitions in 6.8.2 [basic.fundamental], the arithmetic types include only the non-cv-qualified versions. In the taxonomy of fundamental types, the first mention of “cv-qualified versions of these types” is for scalar types (6.8 [basic.types] paragraph 9). However, 7.6.1.6 [expr.post.incr] paragraph 1 and 7.6.2.3 [expr.pre.incr] paragraph 1 both say:

The type of the operand shall be an arithmetic type other than cv bool, or...

which is a contradiction, since cv-qualified bool is not an arithmetic type. Similarly, 7.6.19 [expr.ass] paragraph 6 requires an arithmetic type for += and -=. D.5 [depr.volatile.type] deprecates the increment and decrement operators when applied to volatile-qualified arithmetic types, but the wording already made those ill-formed (since the normative wording requires an arithmetic type and not a possibly cv-qualified version thereof).

A related question is whether 12.5 [over.built], which explicitly allows for cv-qualified arithmetic types, should also note the deprecation.

See also issue 2185.

Notes from the July, 2020 teleconference:

CWG felt that no changes should be made to 12.5 [over.built].

Proposed resolution (April, 2021):

  1. Change 6.8.2 [basic.fundamental] paragraphs 11 and 12 as follows, splitting paragraph 12 as indicated:

  2. Types bool, char, wchar_t, char8_t, char16_t, char32_t, and the signed and unsigned integer types, and cv-qualified versions (6.8.4 [basic.type.qualifier]) thereof, are collectively called termed integral types. A synonym for integral type is integer type. [Note 8: Enumerations (9.7.1 [dcl.enum]) are not integral; however, unscoped enumerations can be promoted to integral types as specified in 7.3.7 [conv.prom]. —end note]

    There are three floating-point types: The three distinct types float, double, and long double can represent floating-point numbers. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double. The types float, double, and long double, and cv-qualified versions (6.8.4 [basic.type.qualifier]) thereof, are collectively termed floating-point types. The value representation of floating-point types is implementation-defined. [Note 9: This document imposes no requirements on the accuracy of floating-point operations; see also 17.3 [support.limits]. —end note]

    Integral and floating-point types are collectively called termed arithmetic types. Specializations of the standard library template std::numeric_limits (17.3 [support.limits]) shall specify the maximum and minimum values of each arithmetic type for an implementation.

  3. Change 6.8.4 [basic.type.qualifier] paragraph 1 as follows, splitting the paragraph as indicated:

  4. A type mentioned in 6.8.2 [basic.fundamental] and 6.8.3 [basic.compound] is a cv-unqualified type. Each type which is a cv-unqualified object type or is void (6.8 [basic.types]) has three corresponding cv-qualified versions of its type other than a function or reference type is part of a group of four distinct, but related, types: a cv-unqualified version, a const-qualified version, a volatile-qualified version, and a const-volatile-qualified version. The type of an object (6.7.2 [intro.object]) includes the cv-qualifiers specified in the decl-specifier-seq (9.2 [dcl.spec]), declarator (9.3 [dcl.decl]), type-id (9.3.2 [dcl.name]), or new-type-id (7.6.2.8 [expr.new]) when the object is created. The types in each such group shall have the same representation and alignment requirements (6.7.6 [basic.align]). [Footnote: The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and non-static data members of unions. —end footnote] A function or reference type is always cv-unqualified.

    The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (6.7.6 [basic.align]).40 [Note: The type of an object (6.7.2 [intro.object]) includes the cv-qualifiers specified in the decl-specifier-seq (9.2 [dcl.spec]), declarator (9.3 [dcl.decl]), type-id (9.3.2 [dcl.name]), or new-type-id (7.6.2.8 [expr.new]) when the object is created. —end note]

  5. Change 12.5 [over.built] paragraphs 2-10 as follows:

  6. In this subclause, the term promoted integral type is used to refer to those cv-unqualified integral types which are preserved by integral promotion (7.3.7 [conv.prom]) (including e.g. int and long but excluding e.g. char ). [Note 2: In all cases where a promoted integral type is required, an operand of unscoped enumeration type will be acceptable by way of the integral promotions. —end note]

    In the remainder of this subclause, vq represents either volatile or no cv-qualifier.

    For every pair (T, vq), where T is an a cv-unqualified arithmetic type other than bool or a cv-unqualified pointer to (possibly cv-qualified) object type, there exist candidate operator functions of the form

    For every pair (T, vq), where T is an arithmetic type other than bool, there exist candidate operator functions of the form

    For every pair (T, vq), where T is a cv-qualified or cv-unqualified object type, there exist candidate operator functions of the form

    For every cv-qualified or cv-unqualified (possibly cv-qualified) object type T and for every function type T that has neither cv-qualifiers nor a ref-qualifier, there exist candidate operator functions of the form

    For every function type T that does not have cv-qualifiers or a ref-qualifier, there exist candidate operator functions of the form

    For every type T there exist candidate operator functions of the form

    For every cv-unqualified floating-point or promoted integral type T, there exist candidate operator functions of the form

[Drafting note: Clause 21 [meta] regarding type traits appropriately handles cv-qualified and cv-unqualified types and does not require revision.]




2499. Inconsistency in definition of pointer-interconvertibility

Section: 6.8.3  [basic.compound]     Status: DRWP     Submitter: Jason Merrill     Date: 2021-07-29

[Accepted at the February, 2022 meeting.]

The changes for issue 2254 included the following:

Change 6.8.3 [basic.compound] bullet 4.3 as follows:

Two objects a and b are pointer-interconvertible if:

This should also have removed the phrase,

or, if the object has no non-static data members,

since the change to 11.4 [class.mem] paragraph 25 specifies that all bases of a standard-layout class have the same address, regardless of whether the derived class has non-static data members.

Proposed resolution (November, 2021):

Change 6.8.3 [basic.compound] bullet 4.3 as follows:

Two objects a and b are pointer-interconvertible if:




2479. Missing specifications for consteval and constinit

Section: 6.9.3.1  [basic.start.main]     Status: DRWP     Submitter: Davis Herring     Date: 2020-10-09

[Accepted as a DR at the June, 2021 meeting.]

There are several places where the consteval and/or constinit keywords should be mentioned but are not:

6.9.3.1 [basic.start.main] paragraph 3:

A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed.

9.3.4.1 [dcl.meaning.general] paragraph 2:

A static, thread_local, extern, mutable, friend, inline, virtual, constexpr, or typedef specifier or an explicit-specifier applies directly to each declarator-id in an init-declarator-list or member-declarator-list...

11.4.5.1 [class.ctor.general] paragraph 1:

...In a constructor declaration, each decl-specifier in the optional decl-specifier-seq shall be friend, inline, constexpr, or an explicit-specifier.

Proposed resolution, May, 2021:

  1. Change 6.9.3.1 [basic.start.main] paragraph 3 as follows:

  2. ...A program that defines main as deleted or that declares main to be inline, static, or constexpr, or consteval is ill-formed...
  3. Change 9.3.4.1 [dcl.meaning.general] paragraph 4 as follows:

  4. A static, thread_local, extern, mutable, friend, inline, virtual, constexpr, consteval, constinit, or typedef specifier or an explicit-specifier applies directly to each declarator-id in a declaration; the type specified for each declarator-id depends on both the decl-specifier-seq and its declarator.
  5. Change 11.4.5.1 [class.ctor.general] paragraph 5 as follows:

  6. ...Constructors do not have names. In a constructor declaration, each decl-specifier in the optional decl-specifier-seq shall be friend, inline, constexpr, consteval, or an explicit-specifier.



2484. char8_t and char16_t in integral promotions

Section: 7.3.7  [conv.prom]     Status: DRWP     Submitter: Richard Smith     Date: 2021-04-01

[Accepted as a DR at the October, 2021 meeting.]

According to 7.3.7 [conv.prom] paragraphs 1-2,

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (6.8.5 [conv.rank]) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

A prvalue of type char16_t, char32_t, or wchar_t (6.8.2 [basic.fundamental]) can be converted to a prvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. If none of the types in that list can represent all the values of its underlying type, a prvalue of type char16_t, char32_t, or wchar_t can be converted to a prvalue of its underlying type.

Because of its omission from the list of excluded types (perhaps as an oversight when it was added), char8_t is handled in the first paragraph. However, char16_t falls into the second paragraph, even though it is guaranteed to be convertible to int or unsigned int. This seems inconsistent, so perhaps char8_t should be moved to the second paragraph or char16_t moved to the first?

Notes from the August, 2021 teleconference:

char8_t should be handled by the second paragraph by including it in all three lists of types in the two paragraphs.

Proposed resolution (August, 2021):

Change 7.3.7 [conv.prom] paragraphs 1 and 2 as follows:

A prvalue of an integer type other than bool, char8_t, char16_t, char32_t, or wchar_t whose integer conversion rank (6.8.5 [conv.rank]) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

A prvalue of type char8_t, char16_t, char32_t, or wchar_t (6.8.2 [basic.fundamental]) can be converted to a prvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. If none of the types in that list can represent all the values of its underlying type, a prvalue of type char8_t, char16_t, char32_t, or wchar_t can be converted to a prvalue of its underlying type.




2396. Lookup of names in complex conversion-type-ids

Section: 7.5.4.3  [expr.prim.id.qual]     Status: DRWP     Submitter: Richard Smith     Date: 2018-12-03

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Issue 2385 assumed a simple case where a conversion-type-id is an identifier. More complex cases need to be addressed as well. For example:

  struct A {
    struct B;
    operator B B::*();
  };
  struct B;
  void f(A a) { a.operator B B::*(); }            // first B is A::B. what is second B? 
  void g(A a) { a.operator decltype(B()) B::*();} // what about the operand of decltype? 
  void h(A a) { a.operator X<B>(); }              // what is B here? 



1822. Lookup of parameter names in lambda-expressions

Section: 7.5.5  [expr.prim.lambda]     Status: DRWP     Submitter: Steve Clamage     Date: 2013-12-10

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 7.5.5 [expr.prim.lambda] paragraph 7, names appearing in the compound-statement of a lambda-expression are looked up in the context of the lambda-expression, ignoring the fact that the compound-statement will be transformed into the body of the closure type's function operator. This leaves unspecified how the lambda-expression's parameters are found by name lookup. Presumably the parameters hide the corresponding names from the surrounding scope, but this needs to be specified.




2509. decl-specifier-seq in lambda-specifiers

Section: 7.5.5.1  [expr.prim.lambda.general]     Status: DRWP     Submitter: Jens Maurer     Date: 2021-10-28

[Accepted at the February, 2022 meeting.]

(From editorial issue 2338.)

Use of decl-specifier-seq in the production for lambda-specifiers is too general and should be restricted.

Proposed resolution (December, 2021):

  1. Change the grammar in 7.5.5.1 [expr.prim.lambda.general] as follows:

  2. Change 7.5.5.1 [expr.prim.lambda.general] paragrap 3 as follows:

  3. In the decl-specifier-seq of the lambda-declarator, each decl-specifier shall be one of mutable, constexpr, or consteval. A lambda-specifier-seq shall contain at most one of each lambda-specifier and shall not contain both constexpr and consteval. If the lambda-declarator contains an explicit object parameter (9.3.4.6 [dcl.fct]), then no decllambda-specifier in the decllambda-specifier-seq shall be mutable.



1249. Cv-qualification of nested lambda capture

Section: 7.5.5.3  [expr.prim.lambda.capture]     Status: DRWP     Submitter: James Widman     Date: 2011-03-02

[Accepted as a DR at the October, 2021 meeting.]

Consider the following example:

    void f(int i) {
      auto l1 = [i] {
        auto l2 = [&i] {
          ++i;    // Well-formed?
        };
      };
    }

Because the l1 lambda is not marked as mutable, its operator() is const; however, it is not clear from the wording of 7.5.5 [expr.prim.lambda] paragraph 16 whether the captured member of the enclosing lambda is considered const or not.

Proposed resolution (August, 2021):

Change 7.5.5.3 [expr.prim.lambda.capture] paragraph 14 as follows:

If a lambda-expression m2 captures an entity and that entity is captured by an immediately enclosing lambda-expression m1, then m2's capture is transformed as follows:




2486. Call to noexcept function via noexcept(false) pointer/lvalue

Section: 7.6.1.3  [expr.call]     Status: DRWP     Submitter: Jiang An     Date: 2021-03-27

[Accepted as a DR at the October, 2021 meeting.]

According to 7.6.1.3 [expr.call] paragraph 6,

Calling a function through an expression whose function type is different from the function type of the called function's definition results in undefined behavior.

This restriction should exempt calling a noexcept function where the function type of the expression is identical except that it is noexcept(false).

In addition, 7.6.1.9 [expr.static.cast] paragraph 7 currently forbids static_cast from converting a function pointer or member function pointer from noexcept(false) to noexcept:

The inverse of any standard conversion sequence (7.3 [conv]) not containing an lvalue-to-rvalue (7.3.2 [conv.lval]), array-to-pointer (7.3.3 [conv.array]), function-to-pointer (7.3.4 [conv.func]), null pointer (7.3.12 [conv.ptr]), null member pointer (7.3.13 [conv.mem]), boolean (7.3.15 [conv.bool]), or function pointer (7.3.14 [conv.fctptr]) conversion, can be performed explicitly using static_cast.

This restriction should also be relaxed, allowing binding a constexpr reference to the result of the reversed conversion.

Notes from the August, 2021 teleconference:

CWG agreed that it should be permitted to call a noexcept function via an expression that is noexcept(false); since the implicit conversion is allowed, the failure to allow the call is clearly just an oversight. The question of whether to allow the static_cast in the inverse direction, as well as whether to allow calling a noexcept(false) function via a noexcept expression (which would result in undefined behavior only if the function actually threw an exception) was deemed to be a matter for EWG and was thus split off into issue 2500.

Proposed resolution (September, 2021):

Change 7.6.1.3 [expr.call] paragraph 6 as follows:

Calling a function through an expression whose function type E is different from the function type F of the called function's definition results in undefined behavior unless the type “pointer to F” can be converted to the type “pointer to E” via a function pointer conversion (7.3.14 [conv.fctptr]). [Note: The exception applies when the expression has the type of a potentially-throwing function, but the called function has a non-throwing exception specification, and the function types are otherwise the same. —end note]



2458. Value category of expressions denoting non-static member functions

Section: 7.6.1.5  [expr.ref]     Status: DRWP     Submitter: Andrey Erokhin     Date: 2020-07-04

[Accepted as a DR at the June, 2021 meeting.]

Expressions denoting non-static member functions are currently classified as prvalues (7.5.4.3 [expr.prim.id.qual] paragraph 2; 7.6.1.5 [expr.ref] bullet 6.3.2; and 7.6.4 [expr.mptr.oper] paragraph 6). It would simplify the specification if such expressions were categorized as lvalues. (See also this pull request.)

Notes from the August, 2020 teleconference:

CWG preferred that the unbound case (i.e., &X::f) should be an lvalue, while the bound case should be a prvalue.

Proposed resolution (April, 2021):

  1. Change 7.5.4.3 [expr.prim.id.qual] paragraph 5, converting the running text into a bulleted list, as follows:

  2. The result of a qualified-id Q is the entity it denotes (6.5.5 [basic.lookup.qual]). The type of the expression is the type of the result. The result is an lvalue if the member is

    and a prvalue otherwise.

  3. Change 7.6.2.2 [expr.unary.op] paragraph 3 as follows:

  4. The result of the The operand of the unary & operator shall be an lvalue of some type T. The result is a pointer to its operand prvalue.

[Drafting note: neither 7.6.1.5 [expr.ref] bullet 6.3.2,

nor 7.6.4 [expr.mptr.oper] paragraph 6,

...The result of a .* expression whose second operand is a pointer to a member function is a prvalue...

requires any change.]




2466. co_await should be a single evaluation

Section: 7.6.2.4  [expr.await]     Status: DRWP     Submitter: Gor Nishanov     Date: 2020-10-19

[Accepted as a DR at the June, 2021 meeting.]

The description of co_await should not permit reordering the subexpressions constituting the evaluation of a co_await expression. For example, given

  auto z = co_await coro + co_await coro;

the result may be different from the expected

  auto x = co_await coro;
  auto y = co_await coro;
  auto z = x + y;

Suggested resolution:

Add the following as a new paragraph following 7.6.2.4 [expr.await] paragraph 5:

With respect to an indeterminately-sequenced function call, the operation of co_await is a single evaluation. [Note: Therefore a function call cannot intervene between the subexpressions constituting evaluation of a co_await expression. —end note]

[Example 1:...

Proposed resolution, May, 2021:

  1. Change 6.9.1 [intro.execution] paragraph 11 as follows:

  2. When calling invoking a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with and the postfix expression designating the called function, is are sequenced before execution of every expression or statement in the body of the called function. For each function invocation or evaluation of an await-expression F, for every each evaluation A that occurs does not occur within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any), either A is sequenced before B or B is sequenced before A. is either sequenced before all evaluations that occur within F or sequenced after all evaluations that occur within F; [Footnote: In other words, function executions do not interleave with each other. —end footnote] if F invokes or resumes a coroutine (7.6.2.4 [expr.await]), only evaluations subsequent to the previous suspension (if any) and prior to the next suspension (if any) are considered to occur within F. [Note 7: If A and B would not otherwise be sequenced then they are indeterminately sequenced. —end note]
  3. Add the following note at the end of 7.6.2.4 [expr.await] paragraph 5:

  4. The await-expression evaluates the (possibly-converted) o expression and the await-ready expression, then:

    [Note: With respect to sequencing, an await-expression is indivisible (6.9.1 [intro.execution]). —end note]

Drafting note: No change is needed in 6.9.1 [intro.execution] paragraph 8:

...An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.

Additional note, May, 2021:

Note 7 in 6.9.1 [intro.execution] paragraph 11 refers to evaluations A and B, even though the edit to that paragraph above removes those names. This discrepancy was noticed only after CWG approved the change to the normative wording. Since it involves only the wording of a non-normative note, the problem will be addressed editorially. See editorial issue 4612.




2474. Cv-qualification and deletion

Section: 7.6.2.9  [expr.delete]     Status: DRWP     Submitter: Unknown     Date: 2020-10-29

[Accepted as a DR at the June, 2021 meeting.]

(From editorial issue 4305.)

According to 7.6.2.9 [expr.delete] paragraph 3,

In a single-object delete expression, if the static type of the object to be deleted is different from its dynamic type and the selected deallocation function (see below) is not a destroying operator delete, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In an array delete expression, if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

Both the static type and the dynamic type include cv-qualification, and requiring agreement in qualification between the two for deletion is not intended. Perhaps the restriction should be to similar types instead of identical types?

Notes from the December, 2020 teleconference:

“Similar types” raises issues with arrays of unknown bounds, but a change to allow for differences in cv-qualification is needed.

Notes from the May 25, 2021 teleconference:

It was observed that current implementations store the total number of class objects in a multi-dimensional array in a “cookie” in the array allocation overhead, rather than the number of top-level array elements, and thus are able to invoke the destructors correctly even if the type being deleted is an array of unknown bound. Consequently, it was decided that use of the “similar” criterion was appropriate.

Proposed resolution, May, 2021:

Change 7.6.2.9 [expr.delete] paragraph 3 as follows:

In a single-object delete expression, if the static type of the object to be deleted is different from not similar (7.3.6 [conv.qual]) to its dynamic type and the selected deallocation function (see below) is not a destroying operator delete, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In an array delete expression, if the dynamic type of the object to be deleted differs from is not similar to its static type, the behavior is undefined.



2490. Restrictions on destruction in constant expressions

Section: 7.7  [expr.const]     Status: DRWP     Submitter: Jiang An     Date: 2021-05-04

[Accepted as a DR at the October, 2021 meeting.]

According to 7.7 [expr.const] paragraph 6,

For the purposes of determining whether an expression E is a core constant expression, the evaluation of a call to a member function of std::allocator<T> as defined in 20.2.9.2 [allocator.members], where T is a literal type, does not disqualify E from being a core constant expression, even if the actual evaluation of such a call would otherwise fail the requirements for a core constant expression. Similarly, the evaluation of a call to std::destroy_at, std::ranges::destroy_at, std::construct_at, or std::ranges::construct_at does not disqualify E from being a core constant expression unless:

There are, however, no specific restrictions in 7.7 [expr.const] regarding destructor or pseudo-destructor calls. In particular, a constexpr destructor can be called for any object, regardless of how it was constructed or the start of its lifetime, and similarly for pseudo-destructor calls. This seems inconsistent.

If those restrictions are added, would the specific restrictions on library destruction facilities still be needed?

Notes from the August, 2021 teleconference:

CWG agreed that since trivial destructors and pseudo-destructors are now considered to end the lifetime of the object for which they are called, they should be prohibited from being invoked for a runtime object in a constant expression.

Proposed resolution (August, 2021):

  1. Change 7.7 [expr.const] paragraph 5 as follows:

  2. An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine (6.9.1 [intro.execution]), would evaluate one of the following:

  3. Change 7.7 [expr.const] paragraph 6 as follows, merging the single remaining bulleted item into the running text of the paragraph:

  4. For the purposes of determining whether an expression E is a core constant expression, the evaluation of a call to a member function of std::allocator<T> as defined in 20.2.9.2 [allocator.members], where T is a literal type, does not disqualify E from being a core constant expression, even if the actual evaluation of such a call would otherwise fail the requirements for a core constant expression. Similarly, the evaluation of a call to std::destroy_at, std::ranges::destroy_at, std::construct_at, or std::ranges::construct_at does not disqualify E from being a core constant expression unless:




2452. Flowing off the end of a coroutine

Section: 8.7.5  [stmt.return.coroutine]     Status: DRWP     Submitter: Lewis Baker     Date: 2020-02-14

[Accepted at the November, 2020 meeting.]

There are two references to “flowing off the end of a coroutine”, specifically in 8.7.5 [stmt.return.coroutine] paragraph 3:

If p.return_void() is a valid expression, flowing off the end of a coroutine is equivalent to a co_return with no operand; otherwise flowing off the end of a coroutine results in undefined behavior.

and 9.5.4 [dcl.fct.def.coroutine] paragraph 11:

The coroutine state is destroyed when control flows off the end of the coroutine or...

These mean different things and should be clarified.

Proposed resolution (July, 2020):

Change 8.7.5 [stmt.return.coroutine] paragraph 3 as follows:

If p.return_void() is a valid expression, flowing off the end of a coroutine's function-body is equivalent to a co_return with no operand;otherwise flowing off the end of a coroutine's function-body results in undefined behavior.



1616. Disambiguation parsing and template parameters

Section: 8.9  [stmt.ambig]     Status: DRWP     Submitter: Johannes Schaub     Date: 2013-02-01

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 8.9 [stmt.ambig] paragraph 3,

The disambiguation is purely syntactic; that is, the meaning of the names occurring in such a statement, beyond whether they are type-names or not, is not generally used in or changed by the disambiguation. Class templates are instantiated as necessary to determine if a qualified name is a type-name. Disambiguation precedes parsing, and a statement disambiguated as a declaration may be an ill-formed declaration. If, during parsing, a name in a template parameter is bound differently than it would be bound during a trial parse, the program is ill-formed. No diagnostic is required. [Note: This can occur only when the name is declared earlier in the declaration. —end note]

The statement about template parameters is confusing (and not helped by the fact that the example that follows illustrates the general rule for declarations and does not involve any template parameters). It is attempting to say that a program is ill-formed if a template argument of a class template specialization has a different value in the two parses. With decltype this can now apply to other kinds of templates as well, so the wording should be clarified and made more general.




1820. Qualified typedef names

Section: 9.2.4  [dcl.typedef]     Status: DRWP     Submitter: Richard Smith     Date: 2013-12-05

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The resolution of issue 482 allows a typedef to be redeclared in the same or a containing scope using a qualified declarator-id. This was not the principal goal of the issue and is not supported by current implementations. Should the prohibition of qualified declarator-ids be reinstated for typedefs?




1894. typedef-names and using-declarations

Section: 9.2.4  [dcl.typedef]     Status: DRWP     Submitter: Richard Smith     Date: 2014-03-16

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The resolution of issue 407 does not cover cases involving using-declarations. For example:

  namespace A { struct S {}; }
  namespace B {
    // This is valid per issue 407
    using A::S;
    typedef A::S S;
    struct S s;
  }
  namespace C {
    // The typedef does not redefine the name S in this
    // scope, so issue 407's resolution does not apply.
    typedef A::S S;
    using A::S;
    // The name lookup here isn't ambiguous, because it only finds one
    // entity, but it finds both a typedef-name and a non-typedef-name referring
    // to that entity, so the standard doesn't appear to say whether this is valid.
    struct S s;
  }

The same issue appears with using-directives:

  namespace D { typedef A::S S; }
  namespace E {
    using namespace A;
    using namespace D;
    struct S s; // ok? issue 407 doesn't apply here either
  }

One possibility might be to remove the rule that a typedef-name declaration redefines an already-defined name and instead rely on struct stat-style hiding, taking the non-typedef-name if name lookup finds both and they refer to the same type.

Notes from the June, 2014 meeting:

CWG felt that these examples should be well-formed.




2199. Typedefs and tags

Section: 9.2.4  [dcl.typedef]     Status: DRWP     Submitter: Richard Smith     Date: 2015-11-12

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

It is still unclear how typedefs and elaborated-type-specifiers interact in some cases. For example:

    namespace A {
      struct S {};
    }
    namespace B {
      typedef int S;
    }
    namespace C {
      using namespace A;
      using namespace B;
      struct S s; // clearly ambiguous, S names different entities
    }
    namespace D {
      using A::S;
      typedef struct S S;
      struct S s; // OK under issue 407: S could be used in an
                  //  elaborated-type-specifier before the typedef, so still can be
    }
    namespace E {
      typedef A::S S;
      using A::S;
      struct S s; // ??? the identifier S could not have been used in an
                  // elaborated-type-specifier prior to the typedef, so is this lookup
                  // ill-formed because it finds a typedef-name?
    }
    namespace F {
      typedef A::S S;
    }
    namespace G {
      using namespace A;
      using namespace F;
      struct S s; // ??? F::S could not have been used as an
                  // elaborated-type-specifier before the typedef. is this ill-formed because
                  // the lookup finds a typedef-name?
    }
    namespace H {
      using namespace F;
      using namespace A;
      struct S s; // some implementations give different answers for G and H
    }



2213. Forward declaration of partial specializations

Section: 9.2.9.4  [dcl.type.elab]     Status: DRWP     Submitter: Richard Smith     Date: 2015-12-11

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 9.2.9.4 [dcl.type.elab] paragraph 1,

If an elaborated-type-specifier is the sole constituent of a declaration, the declaration is ill-formed unless it is an explicit specialization (13.9.4 [temp.expl.spec]), an explicit instantiation (13.9.3 [temp.explicit]) or it has one of the following forms:

This implies that class template partial specializations cannot be forward-declared, which is probably unintentional.

Notes from the November, 2016 meeting:

CWG felt that forward declarations of partial specializations should be allowed.




1342. Order of initialization with multiple declarators

Section: 9.3  [dcl.decl]     Status: DRWP     Submitter: Alberto Ganesh Barbati     Date: 2011-08-11

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting. See 8.8 [stmt.dcl] paragraph 2.]

It is not clear what, if anything, in the existing specification requires that the initialization of multiple init-declarators within a single declaration be performed in declaration order.




1900. Do friend declarations count as “previous declarations”?

Section: 9.3.4  [dcl.meaning]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-03-25

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Issue 1477 assumes that a name declared only in a friend declaration can be defined outside its namespace using a qualified-id, but the normative passages in 9.3.4 [dcl.meaning] paragraph 1 and _N4868_.9.8.2.3 [namespace.memdef] paragraph 2 do not settle the question definitively, and there is implementation variance. A clearer statement of intent is needed.




2397. auto specifier for pointers and references to arrays

Section: 9.3.4.5  [dcl.array]     Status: DRWP     Submitter: Hubert Tong     Date: 2019-02-04

[Accepted as a DR at the June, 2021 meeting.]

According to 9.3.4.5 [dcl.array] paragraph 1,

In a declaration T D where D has the form

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type; if the type of the identifier of D contains the auto type-specifier, the program is ill-formed.

This formulation forbids useful constructs like

  int a[3];
  auto (*p)[3] = &a;

(accepted by current implementations) and should be relaxed to accommodate such cases.

Notes from the February, 2019 meeting:

CWG agreed that the example should be accepted.

Notes from the May 25, 2021 teleconference:

It was observed that CWG rejected the same example as being "not a defect" in considering issue 1222. However, the use of auto has significantly expanded since that time and the prohibition of such declarations now seems inconsistent.

Proposed resolution, May, 2021:

  1. Change 9.3.4.5 [dcl.array] paragraph 4 as follows:

  2. U is called the array element type; this type shall not be a placeholder type (9.2.9.6 [dcl.spec.auto]), a reference type, a function type, an array of unknown bound, or cv void.
  3. Change 9.3.4.6 [dcl.fct] paragraph 11 as follows:

  4. The return type shall be a non-array object type, a reference type, or cv void. [Note: An array of placeholder type is considered an array type. —end note]
  5. Change 9.2.9.6.2 [dcl.type.auto.deduct] paragraph 2 as follows:

  6. A type T containing a placeholder type, and a corresponding initializer E, are determined as follows:

    T shall not be an array type. In the case of a return statement with no operand...




2481. Cv-qualification of temporary to which a reference is bound

Section: 9.4.4  [dcl.init.ref]     Status: DRWP     Submitter: Jiang An     Date: 2021-03-20

[Accepted as a DR at the June, 2021 meeting.]

According to 9.4.4 [dcl.init.ref] bullet 5.4.2, when a reference is initialized with a non-class value and the referenced type is not reference-related to the type of the initializer,

According to 7.2.2 [expr.type] paragraph 2, the cv-qualification is discarded before invoking the temporary materialization conversion:

If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

This results in a reference-to-const being bound to a non-const object, meaning that a const_cast of the reference to a reference-to-nonconst would allow a well-defined modification of the value:

  constexpr const int &r = 42;
  const_cast<int &>(r) = 23;  // Well-defined
  static_assert(r == 42);     // Ill-formed, non-constant expression

This was different from the situation before the advent of the temporary materialization conversion in C++17, when the description of the reference binding created the temporary explicitly with the cv-qualified type:

If T1 is a non-class type, a temporary of type “cv1 T1” is created and copy-initialized (8.5) from the initializer expression. The reference is then bound to the temporary.

Presumably this difference was unintentional and should be reverted.

Proposed resolution, May, 2021:

Change 9.4.4 [dcl.init.ref] bullet 5.4.2 as follows:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:




1733. Return type and value for operator= with ref-qualifier

Section: 9.5.2  [dcl.fct.def.default]     Status: DRWP     Submitter: James Widman     Date: 2013-08-09

[Accepted as a DR at the October, 2021 meeting.]

9.5.2 [dcl.fct.def.default] paragraph 1 specifies that an explicitly-defaulted function shall

have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const T”, where T is the name of the member function's class) as if it had been implicitly declared...

This allows an example like

  struct A {
    A& operator=(A const&) && = default;
  };

but forbids

  struct B {
    B&& operator=(B const&) && = default;
  };

which seems backward.

In addition, 11.4.5.3 [class.copy.ctor] paragraph 22 only specifies the return value for implicitly-declared copy/move assignment operators, not for explicitly-defaulted ones.

Proposed resolution (August, 2021):

  1. Change 11.4.6 [class.copy.assign] paragraph 6 as follows:

  2. The implicitly-declared copy/move assignment operator for class X has the return type X&; it returns the object for which the assignment operator is invoked, that is, the object assigned to. An implicitly-declared copy/move assignment operator is an inline public member of its class.
  3. Add the following as a new paragraph following 11.4.6 [class.copy.assign] paragraph 13:

  4. The implicitly-defined copy assignment operator for a union X copies the object representation (6.8 [basic.types]) of X. If the source and destination of the assignment are not the same object, then for each object nested within (6.7.2 [intro.object]) the object that is the source of the copy, a corresponding object o nested within the destination is created, and the lifetime of o begins before the copy is performed.

    The implicitly-defined copy/move assignment operator for a class returns the object for which the assignment operator is invoked, that is, the object assigned to.

[Note: The first point in the issue, that of the relationship between the ref-qualifier and the return type, will be referred to EWG for consideration. The draft resolution above addresses only the second point of the issue.




2465. Coroutine parameters passed to a promise constructor

Section: 9.5.4  [dcl.fct.def.coroutine]     Status: DRWP     Submitter: Gor Nishanov     Date: 2020-10-19

[Accepted as a DR at the June, 2021 meeting.]

The resolution of issue 2436 (in P2107R0) deleted the sentence

A reference to a parameter in the function-body of the coroutine and in the call to the coroutine promise constructor is replaced by a reference to its copy.

replacing it with new wording in 7.5.4.2 [expr.prim.id.unqual] paragraph 1:

An identifier that names a coroutine parameter refers to the copy of the parameter (9.5.4 [dcl.fct.def.coroutine]).

This new approach no longer covers coroutine parameters passed to a promise constructor, since the constructor call is implicit, as described in 7.5.4.2 [expr.prim.id.unqual] paragraph 5.

Suggested resolution:

  1. Change 7.5.4.2 [expr.prim.id.unqual] paragraph 4 as follows:

  2. In the following, pi is an lvalue of type Pi, where p1 denotes *this and pi+1 denotes the ith function parameter for a non-static member function, and pi denotes the ith function parameter otherwise. Let qi be the corresponding parameter copy, as described below.
  3. Change 7.5.4.2 [expr.prim.id.unqual] bullet 5.7 as follows:

  4. A coroutine behaves as if its function-body were replaced by...

Proposed resolution (April, 2021):

  1. Change 9.5.4 [dcl.fct.def.coroutine] paragraph 4 as follows:

  2. In the following, pi is an lvalue of type Pi, where p1 denotes *this and pi+1 denotes the ith function parameter for a non-static member function, and pi denotes the ith function parameter otherwise. For a non-static member function, q1 is an lvalue that denotes *this; any other qi is an lvalue that denotes the parameter copy corresponding to pi, as described below.
  3. Change 9.5.4 [dcl.fct.def.coroutine] bullet 5.7 as follows:

  4. A coroutine behaves as if its function-body were replaced by: ... where




2312. Structured bindings and mutable

Section: 9.6  [dcl.struct.bind]     Status: DRWP     Submitter: Richard Smith     Date: 2016-08-11

[Accepted at the November, 2020 meeting.]

An example like the following is currently ill-formed:

  struct A { mutable int n; };
  void f() {
    const auto [a] = A();
    a = 0;
  }

According to 9.6 [dcl.struct.bind] paragraph 4, the type of a is const int, since the implicitly-declared variable is const. This seems obviously wrong: the member n is mutable, so the member access expression e.n has type int, which should also be the type of a. (mutable should presumably be taken into account when forming the referenced type too, so that decltype(a) is int as would presumably be expected, rather than const int.)

Proposed resolution, March, 2018: [SUPERSEDED]

Change 9.6 [dcl.struct.bind] paragraph 4 as follows:

...Designating the non-static data members of E as m0, m1, m2, ... (in declaration order), each vi is the name of an lvalue that refers to the member mi of e and whose type is cv Ti, where Ti is the declared type of that member e.mi; the referenced type is cv Ti the type of e.mi. The lvalue is a bit-field if...

Notes from the June, 2018 meeting:

It was observed that this resolution does not handle members with reference type correctly. The main problem seems to be the statement in 7.6.1.5 [expr.ref] paragraph 4, which directly handles members with reference type rather than allowing the type of the member to be the result type and relying on the general rule that turns reference-typed expressions into lvalues.

Proposed resolution (April, 2020):

Change 9.6 [dcl.struct.bind] paragraph 5 as follows:

...Designating the non-static data members of E as m0, m1, m2, ... (in declaration order), each vi is the name of an lvalue that refers to the member mi of e and whose type is cv Ti, where Ti is the declared type of that member that of e.mi (7.6.1.5 [expr.ref]); the referenced type is cv Ti the declared type of mi if that type is a reference type, or the type of e.mi otherwise. The lvalue is a bit-field if that member is a bit-field.

[Example 2:

  struct S { mutable int x1 : 2; volatile double y1; };
  S f();
  const auto [ x, y ] = f();

The type of the id-expression x is “const int”, the type of the id-expression y is “const volatile double”. —end example]




2506. Structured bindings and array cv-qualifiers

Section: 9.6  [dcl.struct.bind]     Status: DRWP     Submitter: Barry Revzin     Date: 2018-12-11

[Accepted at the February, 2022 meeting.]

According to 9.6 [dcl.struct.bind] paragraph 1,

A structured binding declaration introduces the identifiers v0, v1, v2, ... of the identifier-list as names of structured bindings. Let cv denote the cv-qualifiers in the decl-specifier-seq and S consist of the storage-class-specifiers of the decl-specifier-seq (if any). A cv that includes volatile is deprecated; see D.5 [depr.volatile.type]. First, a variable with a unique name e is introduced. If the assignment-expression in the initializer has array type A and no ref-qualifier is present, e is defined by

and each element is copy-initialized or direct-initialized from the corresponding element of the assignment-expression as specified by the form of the initializer.

This means that in an example like

  const int arr[1]{};
  auto [i] = arr;

i is a reference to const int. Presumably the fact that the array is copied should drop the array's cv-qualification.

Proposed resolution (December, 2021):

Change 9.6 [dcl.struct.bind] paragraph 1 as follows:

If the assignment-expression in the initializer has array type cv1 A and no ref-qualifier is present, e is defined by...




36. using-declarations in multiple-declaration contexts

Section: 9.9  [namespace.udecl]     Status: DRWP     Submitter: Andrew Koenig     Date: 20 Aug 1998

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Section 9.9 [namespace.udecl] paragraph 8 says:

A using-declaration is a declaration and can therefore be used repeatedly where (and only where) multiple declarations are allowed.
It contains the following example:
    namespace A {
            int i;
    }

    namespace A1 {
            using A::i;
            using A::i;             // OK: double declaration
    }

    void f()
    {
            using A::i;
            using A::i;             // error: double declaration
    }
However, if "using A::i;" is really a declaration, and not a definition, it is far from clear that repeating it should be an error in either context. Consider:
    namespace A {
            int i;
            void g();
    }

    void f() {
            using A::g;
            using A::g;
    }
Surely the definition of f should be analogous to
    void f() {
            void g();
            void g();
    }
which is well-formed because "void g();" is a declaration and not a definition.

Indeed, if the double using-declaration for A::i is prohibited in f, why should it be allowed in namespace A1?

Proposed Resolution (04/99): Change the comment "// error: double declaration" to "// OK: double declaration". (This should be reviewed against existing practice.)

Notes from 04/00 meeting:

The core language working group was unable to come to consensus over what kind of declaration a using-declaration should emulate. In a straw poll, 7 members favored allowing using-declarations wherever a non-definition declaration could appear, while 4 preferred to allow multiple using-declarations only in namespace scope (the rationale being that the permission for multiple using-declarations is primarily to support its use in multiple header files, which are seldom included anywhere other than namespace scope). John Spicer pointed out that friend declarations can appear multiple times in class scope and asked if using-declarations would have the same property under the "like a declaration" resolution.

As a result of the lack of agreement, the issue was returned to "open" status.

See also issues 56, 85, and 138..

Additional notes (January, 2005):

Some related issues have been raised concerning the following example (modified from a C++ validation suite test):

    struct A
    {
        int i;
        static int j;
    };

    struct B : A { };
    struct C : A { };

    struct D : virtual B, virtual C
    {
        using B::i;
        using C::i;
        using B::j;
        using C::j;
    };

Currently, it appears that the using-declarations of i are ill-formed, on the basis of 9.9 [namespace.udecl] paragraph 10:

Since a using-declaration is a declaration, the restrictions on declarations of the same name in the same declarative region (6.4 [basic.scope]) also apply to using-declarations.

Because the using-declarations of i refer to different objects, declaring them in the same scope is not permitted under 6.4 [basic.scope]. It might, however, be preferable to treat this case as many other ambiguities are: allow the declaration but make the program ill-formed if a name reference resolves to the ambiguous declarations.

The status of the using-declarations of j, however, is less clear. They both declare the same entity and thus do not violate the rules of 6.4 [basic.scope]. This might (or might not) violate the restrictions of 11.4 [class.mem] paragraph 1:

Except when used to declare friends (11.8.4 [class.friend]) or to introduce the name of a member of a base class into a derived class (9.9 [namespace.udecl], _N3225_.11.3 [class.access.dcl]), member-declarations declare members of the class, and each such member-declaration shall declare at least one member name of the class. A member shall not be declared twice in the member-specification, except that a nested class or member class template can be declared and then later defined.

Do the using-declarations of j repeatedly declare the same member? Or is the preceding sentence an indication that a using-declaration is not a declaration of a member?




386. Friend declaration of name brought in by using-declaration

Section: 9.9  [namespace.udecl]     Status: DRWP     Submitter: Herb Sutter     Date: 8 Oct 2002

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The following came up recently on comp.lang.c++.moderated (edited for brevity):

  namespace N1 {
    template<typename T> void f( T* x ) {
      // ... other stuff ...
      delete x;
    }
  }

  namespace N2 {
    using N1::f;

    template<> void f<int>( int* ); // A: ill-formed

    class Test {
      ~Test() { }
      friend void f<>( Test* x );   // B: ill-formed?
    };
  }

I strongly suspect, but don't have standardese to prove, that the friend declaration in line B is ill-formed. Can someone show me the text that allows or disallows line B?

Here's my reasoning: Writing "using" to pull the name into namespace N2 merely allows code in N2 to use the name in a call without qualification (per 9.9 [namespace.udecl]). But just as declaring a specialization must be done in the namespace where the template really lives (hence line A is ill-formed), I suspect that declaring a specialization as a friend must likewise be done using the original namespace name, not obliquely through a "using". I see nothing in 9.9 [namespace.udecl] that would permit this use. Is there?

Andrey Tarasevich: 13.7.5 [temp.friend] paragraph 2 seems to get pretty close: "A friend declaration that is not a template declaration and in which the name of the friend is an unqualified 'template-id' shall refer to a specialization of a function template declared in the nearest enclosing namespace scope".

Herb Sutter: OK, thanks. Then the question in this is the word "declared" -- in particular, we already know we cannot declare a specialization of a template in any other namespace but the original one.

John Spicer: This seems like a simple question, but it isn't.

First of all, I don't think the standard comments on this usage one way or the other.

A similar example using a namespace qualified name is ill-formed based on 9.3.4 [dcl.meaning] paragraph 1:

  namespace N1 {
        void f();
  }

  namespace N2 {
        using N1::f;
        class A {
                friend void N2::f();
        };
  }

Core issue 138 deals with this example:

  void foo();
  namespace A{
    using ::foo;
    class X{
      friend void foo();
    };
  }

The proposed resolution (not yet approved) for issue 138 is that the friend declares a new foo that conflicts with the using-declaration and results in an error.

Your example is different than this though because the presence of the explicit argument list means that this is not declaring a new f but is instead using a previously declared f.

One reservation I have about allowing the example is the desire to have consistent rules for all of the "declaration like" uses of template functions. Issue 275 (in DR status) addresses the issue of unqualified names in explicit instantiation and explicit specialization declarations. It requires that such declarations refer to templates from the namespace containing the explicit instantiation or explicit specialization. I believe this rule is necessary for those directives but is not really required for friend declarations -- but there is the consistency issue.

Notes from April 2003 meeting:

This is related to issue 138. John Spicer is supposed to update his paper on this topic. This is a new case not covered in that paper. We agreed that the B line should be allowed.




852. using-declarations and dependent base classes

Section: 9.9  [namespace.udecl]     Status: DRWP     Submitter: Michael Wong     Date: 2 April, 2009

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The status of an example like the following is unclear in the current Standard:

    struct B {
        void f();
    };
    template<typename T> struct S: T {
        using B::f;
    };

9.9 [namespace.udecl] does not deal explicitly with dependent base classes, but does say in paragraph 3,

In a using-declaration used as a member-declaration, the nested-name-specifier shall name a base class of the class being defined. If such a using-declaration names a constructor, the nested-name-specier shall name a direct base class of the class being defined; otherwise it introduces the set of declarations found by member name lookup (6.5.2 [class.member.lookup], 6.5.5.2 [class.qual]).

In the definition of S, B::f is not a dependent name but resolves to an apparently unrelated class. However, because S could be instantiated as S<B>, presumably 13.8 [temp.res] paragraph 8 would apply:

No diagnostic shall be issued for a template definition for which a valid specialization can be generated.

Note also the resolution of issue 515, which permitted a similar use of a dependent base class named with a non-dependent name.




1907. using-declarations and default arguments

Section: 9.9  [namespace.udecl]     Status: DRWP     Submitter: Richard Smith     Date: 2014-03-30

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The status of an example like the following is not clear:

  void f(int, int);
  template<typename T> void g(T t) { f(t); }
  void f(int, int = 0);
  void h() { g(0); }

According to 13.8.4 [temp.dep.res] paragraph 1,

In resolving dependent names, names from the following sources are considered:

If this is to be interpreted as meaning that only the declarations that are visible at the point of definition can be used in overload resolution for dependent calls, the call g(0) is ill-formed. If, however, it is the names, not the declarations, that are captured, then presumably the second declaration of f should be considered, making the call well-formed. There is implementation divergence for this example.

The resolution of issue 1551 recently clarified the requirements in similar cases involving using-declarations:

  namespace N { void f(int, int); }
  using N::f;
  template<typename T> void g(T t) { f(t); }
  namespace N { void f(int, int = 0); }
  void h() { g(0); }

The note added to 9.9 [namespace.udecl] paragraph 11 makes clear that the call g(0) is well-formed in this example.

This outcome results in an unfortunate discrepancy between how default arguments and overloaded functions are treated, even though default arguments could conceptually be viewed as simply adding extra overloads for the additional arguments.

Notes from the June, 2014 meeting:

CWG was unable to come to consensus regarding the desired outcome, with an approximately equal split between desiring the first example to be well-formed or ill-formed. It was noted that the resolution of issue 1850 makes the corresponding case for non-dependent references ill-formed, with no diagnostic required. Similar questions also apply to completing an array type, which also involves a modification to an existing entity declaration in a given scope.

Notes from the February, 2016 meeting:

CWG determined that the case should be ill-formed, no diagnostic required, to allow implementations to continue to use either strategy.




563. Linkage specification for objects

Section: 9.11  [dcl.link]     Status: DRWP     Submitter: Daveed Vandevoorde     Date: 8 March 2006

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

It is not clear whether some of the wording in 9.11 [dcl.link] that applies only to function types and names ought also to apply to object names. In particular, paragraph 3 says,

Every implementation shall provide for linkage to functions written in the C programming language, "C", and linkage to C++ functions, "C++".

Nothing is said about variable names, apparently meaning that implementations need not provide C (or even C++!) linkage for variable names. Also, paragraph 5 says,

Except for functions with C++ linkage, a function declaration without a linkage specification shall not precede the first linkage specification for that function. A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.

There doesn't seem to be a good reason for these provisions not to apply to variable names, as well.




1818. Visibility and inherited language linkage

Section: 9.11  [dcl.link]     Status: DRWP     Submitter: Richard Smith     Date: 2013-12-04

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Does the language linkage of a block-scope declaration determine the language linkage of a subsequent declaration of the same name in a different scope? For example,

   extern "C" void f() {
     void g();    // Implicitly extern "C"
   }
   void g() { }   // Also extern "C" or linkage mismatch?

In other contexts, inheritance of linkage requires that the earlier declaration be visible, as in 6.6 [basic.link] paragraph 6:

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration.

The specification for language linkage in 9.11 [dcl.link] paragraph 5, however, makes no mention of visibility:

A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.



2460. C language linkage and constrained non-template friends

Section: 9.11  [dcl.link]     Status: DRWP     Submitter: Hubert Tong     Date: 2020-03-23

[Accepted at the November, 2020 meeting.]

According to 13.7.5 [temp.friend] paragraph 9,

A non-template friend declaration with a requires-clause shall be a definition. A friend function template with a constraint that depends on a template parameter from an enclosing template shall be a definition. Such a constrained friend function or function template declaration does not declare the same function or function template as a declaration in any other scope.

However, this specification conflicts with the treatment of functions with C language linkage in 9.11 [dcl.link] paragraph 7:

At most one function with a particular name can have C language linkage. Two declarations for a function with C language linkage with the same function name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same function.

For example:

  template <typename T> struct A { struct B; };

  extern "C" {
  template <typename T>
  struct A<T>::B {
   friend void f(B *) requires true {} // C language linkage applies
  };
  }

  namespace Q {
   extern "C" void f(); // ill-formed redeclaration?
  }

Proposed resolution (April, 2020):

Change 9.11 [dcl.link] paragraph 5 as follows:

...A C language linkage is ignored in determining the language linkage of the names of class members, the names of friend functions with a trailing requires-clause, and the function type of class member functions...



2491. Export of typedef after its first declaration

Section: 10.2  [module.interface]     Status: DRWP     Submitter: Richard Smith     Date: 2021-04-16

[Accepted as a DR at the October, 2021 meeting.]

According to 10.2 [module.interface] paragraph 6,

A redeclaration of an entity or typedef-name X is implicitly exported if X was introduced by an exported declaration; otherwise it shall not be exported. [Example 4:

  export module M;
  struct S { int n; };
  typedef S S;
  export typedef S S; // OK, does not redeclare an entity
  export struct S;    // error: exported declaration follows non-exported declaration

end example]

The normative text says that exporting a typedef that was not exported on its first declaration is ill-formed, but the example does so and states that it is “OK”. This is a contradiction that was introduced by the changes in paper P1787R6; the previous normative text supported the usage in the example.

(See also editorial issue 4540.)

Proposed resolution, August, 2021:

Change 10.2 [module.interface] paragraph 6 as follows:

A redeclaration of an entity or typedef-name X is implicitly exported if X was introduced by an exported declaration; otherwise it shall not be exported.



1821. Qualified redeclarations in a class member-specification

Section: 11.4  [class.mem]     Status: DRWP     Submitter: Richard Smith     Date: 2013-1205

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

11.4 [class.mem] paragraph 1 allows nested classes, class templates, and enumerations to be declared and then later defined in the class member-specification. There does not appear to be a restriction on using a qualified-id in that definition. Should such a restriction be added?




2477. Defaulted vs deleted copy constructors/assignment operators

Section: 11.4.5.3  [class.copy.ctor]     Status: DRWP     Submitter: Andrew Rogers     Date: 2021-02-04

[Accepted as a DR at the June, 2021 meeting.]

According to 11.4.5.3 [class.copy.ctor] paragraph 6,

If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (9.5 [dcl.fct.def]).

However, this rule is contradicted by paragraph 10, which lists a number of other reasons why a defaulted copy constructor will be defined as deleted, rather than being “defined as defaulted,” as required by paragraph 6:

A defaulted copy/move constructor for a class X is defined as deleted (9.5.3 [dcl.fct.def.delete]) if X has:

A similar contradiction exists for copy assignment operators in 11.4.6 [class.copy.assign] paragraphs 2 and 7.

Proposed resolution (April, 2021):

  1. Change 11.4.5.3 [class.copy.ctor] paragraph 6 as follows:

  2. If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (9.5 [dcl.fct.def]). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor (D.8 [depr.impldec]).
  3. Change 11.4.6 [class.copy.assign] paragraph 2 as follows:

  4. If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy assignment operator is defined as deleted; otherwise, it is defined as defaulted (9.5 [dcl.fct.def]). The latter case is deprecated if the class has a user-declared copy constructor or a user-declared destructor (D.9). The implicitly-declared...



399. Destructor lookup redux

Section: 11.4.7  [class.dtor]     Status: DRWP     Submitter: John Spicer     Date: 17 Jan 2003

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Mark Mitchell raised a number of issues related to the resolution of issue 244 and of destructor lookup in general.

Issue 244 says:

... in a qualified-id of the form: the second class-name is looked up in the same scope as the first.

But if the reference is "p->X::~X()", the first class-name is looked up in two places (normal lookup and a lookup in the class of p). Does the new wording mean:

  1. You look up the second class-name in the scope that you found the first one.
  2. You look up the second class-name using the same kind of lookup that found the first one (normal vs. class).
  3. If you did a dual lookup for the first you do a dual lookup for the second.

This is a test case that illustrates the issue:

  struct A {
    typedef A C;
  };

  typedef A B;

  void f(B* bp) {
    bp->B::~B();  // okay B found by normal lookup
    bp->C::~C();  // okay C found by class lookup
    bp->B::~C();  // B found by normal lookup C by class -- okay?
    bp->C::~B();  // C found by class lookup B by normal -- okay?
  }

A second issue concerns destructor references when the class involved is a template class.

  namespace N {
    template <typename T> struct S {
      ~S();
    };
  }

  void f(N::S<int>* s) {
    s->N::S<int>::~S();
  }

The issue here is that the grammar uses "~class-name" for destructor names, but in this case S is a template name when looked up in N.

Finally, what about cases like:

  template <typename T> void f () {
    typename T::B x;
    x.template A<T>::template B<T>::~B();
  }

When parsing the template definition, what checks can be done on "~B"?

Sandor Mathe adds :

The standard correction for issue 244 (now in DR status) is still incomplete.

Paragraph 5 of 6.5.5 [basic.lookup.qual] is not applicable for p->T::~T since there is no nested-name-specifier. Section _N4868_.6.5.6 [basic.lookup.classref] describes the lookup of p->~T but p->T::~T is still not described. There are examples (which are non-normative) that illustrate this sort of lookup but they still leave questions unanswered. The examples imply that the name after ~ should be looked up in the same scope as the name before the :: but it is not stated. The problem is that the name to the left of the :: can be found in two different scopes. Consider the following:

  struct S {
    struct C { ~C() { } };
  };

  typedef S::C D;

  int main() {
    D* p;
    p->C::~D();  // valid?
  }

Should the destructor call be valid? If there were a nested name specifier, then D should be looked for in the same scope as C. But here, C is looked for in 2 different ways. First, it is searched for in the type of the left hand side of -> and it is also looked for in the lexical context. It is found in one or if both, they must match. So, C is found in the scope of what p points at. Do you only look for D there? If so, this is invalid. If not, you would then look for D in the context of the expression and find it. They refer to the same underlying destructor so this is valid. The intended resolution of the original defect report of the standard was that the name before the :: did not imply a scope and you did not look for D inside of C. However, it was not made clear whether this was to be resolved by using the same lookup mechanism or by introducing a new form of lookup which is to look in the left hand side if that is where C was found, or in the context of the expression if that is where C was found. Of course, this begs the question of what should happen when it is found in both? Consider the modification to the above case when C is also found in the context of the expression. If you only look where you found C, is this now valid because it is in 1 of the two scopes or is it invalid because C was in both and D is only in 1?

  struct S {
    struct C { ~C() { } };
  };

  typedef S::C D;
  typedef S::C C;

  int main() {
    D* p;
    p->C::~D();  // valid?
  }

I agree that the intention of the committee is that the original test case in this defect is broken. The standard committee clearly thinks that the last name before the last :: does not induce a new scope which is our current interpretation. However, how this is supposed to work is not defined. This needs clarification of the standard.

Martin Sebor adds this example (September 2003), along with errors produced by the EDG front end:

namespace N {
    struct A { typedef A NA; };
    template <class T> struct B { typedef B NB; typedef T BT; };
    template <template <class> class T> struct C { typedef C NC; typedef T<A> CA; };
}

void foo (N::A *p)
{
    p->~NA ();
    p->NA::~NA ();
}

template <class T>
void foo (N::B<T> *p)
{
    p->~NB ();
    p->NB::~NB ();
}

template <class T>
void foo (typename N::B<T>::BT *p)
{
    p->~BT ();
    p->BT::~BT ();
}

template <template <class> class T>
void foo (N::C<T> *p)
{
    p->~NC ();
    p->NC::~NC ();
}

template <template <class> class T>
void foo (typename N::C<T>::CA *p)
{
    p->~CA ();
    p->CA::~CA ();
}

Edison Design Group C/C++ Front End, version 3.3 (Sep  3 2003 11:54:55)
Copyright 1988-2003 Edison Design Group, Inc.

"t.cpp", line 16: error: invalid destructor name for type "N::B<T>"
      p->~NB ();
          ^

"t.cpp", line 17: error: qualifier of destructor name "N::B<T>::NB" does not
          match type "N::B<T>"
      p->NB::~NB ();
              ^

"t.cpp", line 30: error: invalid destructor name for type "N::C<T>"
      p->~NC ();
          ^

"t.cpp", line 31: error: qualifier of destructor name "N::C<T>::NC" does not
          match type "N::C<T>"
      p->NC::~NC ();
              ^

4 errors detected in the compilation of "t.cpp".

John Spicer: The issue here is that we're unhappy with the destructor names when doing semantic analysis of the template definitions (not during an instantiation).

My personal feeling is that this is reasonable. After all, why would you call p->~NB for a class that you just named as N::B<T> and you could just say p->~B?

Additional note (September, 2004)

The resolution for issue 244 removed the discussion of p->N::~S, where N is a namespace-name. However, the resolution did not make this construct ill-formed; it simply left the semantics undefined. The meaning should either be defined or the construct made ill-formed.

See also issues 305 and 466.

Additional note, November, 2014:

Here are some additional examples that should be addressed by the resolution of this issue:

   namespace N {
     template<typename T> struct E {};
     typedef E<int> F;
   }
   namespace M {
     typedef N::F H;
   }
   void g(N::F f) {
     typedef N::F G;
     f.G::~E(); // #1
     f.G::~F(); // #2
     f.G::~G(); // #3
     f.N::F::~E(); // #4
     f.N::F::~F(); // #5
     f.N::F::~G(); // #6
     f.M::H::~E(); // #7
     f.M::H::~F(); // #8
     f.M::H::~G(); // #9
     f.M::H::~H(); // #10
   }



1969. Missing exclusion of ~S as an ordinary function name

Section: 11.4.7  [class.dtor]     Status: DRWP     Submitter: Richard Smith     Date: 2014-07-14

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting. See 11.4.7 [class.dtor] paragraph 1.]

There does not appear to be wording to exclude use of a name like ~S for entities other than destructors.




1726. Declarator operators and conversion function

Section: 11.4.8.3  [class.conv.fct]     Status: DRWP     Submitter: James Widman     Date: 2013-08-02

[Accepted at the February, 2022 meeting.]

Presumably the following example is intended to be ill-formed:

  struct A {
    (*operator int*());
  };
  A a;
  int *x = a; // Ok?

It is not clear, however, which rule is supposed to reject such a member-declaration.

Proposed resolution (December, 2021):

Change 11.4.8.3 [class.conv.fct] paragraph 1 as follows, splitting the paragraph as indicated:

A member function of a class X with a name of the form

A declaration whose declarator-id has an unqualified-id that is a conversion-function-id declares a conversion function; its declarator shall be a function declarator (9.3.4.6 [dcl.fct]) of the form

where the ptr-declarator consists solely of an id-expression, an optional attribute-specifier-seq, and optional surrounding parentheses, and the id-expression has one of the following forms:

A conversion function shall have no parameters and shall be a non-static member function of a class or class template X; it specifies a conversion from X to the type specified by the conversion-type-id, interpreted as a type-id (9.3.2 [dcl.name]). Such functions are called conversion functions.

A decl-specifier in the decl-specifier-seq of a conversion function (if any) shall not be neither a defining-type-specifier nor static. The type of the conversion function (9.3.4.6 [dcl.fct]) is “noexceptopt function taking no parameter cv-qualifier-seqopt ref-qualifieropt returning conversion-type-id”.

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to cv void.102 [Example 1:...




2511. cv-qualified bit-fields

Section: 11.4.10  [class.bit]     Status: DRWP     Submitter: Aaron Ballman     Date: 2021-09-15

[Accepted at the February, 2022 meeting.]

According to 11.4.10 [class.bit] paragraph 1,

A bit-field shall have integral or enumeration type

This apparently does not allow for cv-qualification in a bit-field type.

Notes from the December, 2021 meeting:

As of N4901, there is no longer an issue regarding the integral types; 6.8.2 [basic.fundamental] paragraph 11 says,

The character types, bool, the signed and unsigned integer types, and cv-qualified versions (6.8.4 [basic.type.qualifier]) thereof, are collectively termed integral types.

Proposed resolution (December, 2021):

A bit-field shall have integral or (possibly cv-qualified) enumeration type



255. Placement deallocation functions and lookup ambiguity

Section: 11.4.11  [class.free]     Status: DRWP     Submitter: Mike Miller     Date: 26 Oct 2000

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Paragraph 4 of 11.4.11 [class.free] speaks of looking up a deallocation function. While it is an error if a placement deallocation function alone is found by this lookup, there seems to be an assumption that a placement deallocation function and a usual deallocation function can both be declared in a given class scope without creating an ambiguity. The normal mechanism by which ambiguity is avoided when functions of the same name are declared in the same scope is overload resolution; however, there is no mention of overload resolution in the description of the lookup. In fact, there appears to be nothing in the current wording that handles this case. That is, the following example appears to be ill-formed, according to the current wording:

    struct S {
        void operator delete(void*);
        void operator delete(void*, int);
    };
    void f(S* p) {
        delete p;    // ill-formed: ambiguous operator delete
    }

Suggested resolution (Mike Miller, March 2002):

I think you might get the right effect by replacing the last sentence of 11.4.11 [class.free] paragraph 4 with something like:

After removing all placement deallocation functions, the result of the lookup shall contain an unambiguous and accessible deallocation function.

Additional notes (October, 2012):

This issue should be reconsidered in list of paper N3396, as it would add additional overloads for allocation and deallocation functions.

The term “usual deallocation function” is defined in 6.7.5.5.3 [basic.stc.dynamic.deallocation] paragraph 2; perhaps it could be used to good effect in 7.6.2.9 [expr.delete] paragraph 7. The specifications in 11.4.11 [class.free] paragraphs 4 and 5 should probably also be moved into 7.6.2.9 [expr.delete].




2496. ref-qualifiers and virtual overriding

Section: 11.7.3  [class.virtual]     Status: DRWP     Submitter: Jens Maurer     Date: 2021-06-16

[Accepted as a DR at the October, 2021 meeting.]

According to 11.7.3 [class.virtual] paragraph 2,

If a virtual member function F is declared in a class B, and, in a class D derived (directly or indirectly) from B, a declaration of a member function G corresponds (6.4.1 [basic.scope.scope]) to a declaration of F, ignoring trailing requires-clauses, then G overrides105 F.

This is different from C++20, where G was considered to hide, rather than to override, F if the ref-qualifiers of the declarations are different. This unintentional change could be addressed in one of two ways. To restore the C++20 behavior, the cited paragraph could be amended to:

...a declaration of a member function G corresponds (6.4.1 [basic.scope.scope]) to a declaration of F, ignoring trailing requires-clauses, and has the same ref-qualifier (if any), then G overrides105 F.

Alternatively, such a situation could be regarded as an ill-formed attempt to override the base class function, which could be specified by adding the following as a new paragraph preceding 11.7.3 [class.virtual] paragraph 7:

The ref-qualifier, or lack thereof, of an overriding function shall be the same as that of the overridden function.

The return type of an overriding function shall be either identical to the return type of the overridden function or covariant...

Notes from the August, 2021 teleconference:

CWG preferred the second option.

Proposed resolution, August, 2021:

Add the following as a new paragraph preceding 11.7.3 [class.virtual] paragraph 7:

The ref-qualifier, or lack thereof, of an overriding function shall be the same as that of the overridden function.

The return type of an overriding function shall be either identical to the return type of the overridden function or covariant...




600. Does access control apply to members or to names?

Section: 11.8  [class.access]     Status: DRWP     Submitter: Alisdair Meredith     Date: 3 October 2006

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Referring to a private member of a class, 11.8 [class.access] paragraph 1 says,

its name can be used only by members and friends of the class in which it is declared.

That wording does not appear to reflect the intent of access control, however. Consider the following:

    struct S {
        void f(int);
    private:
        void f(double);
    };

    void g(S* sp) {
        sp->f(2);        // Ill-formed?
    }

The statement from 11.8 [class.access] paragraph 1 says that the name f can be used only by members and friends of S. Function g is neither, and it clearly contains a use of the name f. That appears to make it ill-formed, in spite of the fact that overload resolution will select the public member.

A related question is whether the use of the term “name” in the description of the effect of access control means that it does not apply to constructors and destructors, which do not have names.

Mike Miller: The phrase “its name can be used” should be understood as “it can be referred to by name.” Paragraph 4, among other places, makes it clear that access control is applied after overload resolution. The “name” phrasing is there to indicate that access control does not apply where the name is not used (in a call via a pointer, for example).




360. Using-declaration that reduces access

Section: 11.8.3  [class.access.base]     Status: DRWP     Submitter: Steve Clamage     Date: 4 June 2002

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

I have heard a claim that the following code is valid, but I don't see why.

  struct A {
    int foo ();
  };

  struct B: A {
  private:
    using A::foo;
  };

  int main ()
  {
    return B ().foo ();
  }

It seems to me that the using declaration in B should hide the public foo in A. Then the call to B::foo should fail because B::foo is not accessible in main.

Am I missing something?

Steve Adamczyk: This is similar to the last example in 11.8.3 [class.access.base]. In prose, the rule is that if you have access to cast to a base class and you have access to the member in the base class, you are given access in the derived class. In this case, A is a public base class of B and foo is public in A, so you can access foo through a B object. The actual permission for this is in the fourth bullet in 11.8.3 [class.access.base] paragraph 4.

The wording changes for issue 9 make this clearer, but I believe even without them this example could be discerned to be valid.

See my paper J16/96-0034, WG21/N0852 on this topic.

Steve Clamage: But a using-declaration is a declaration (9.9 [namespace.udecl]). Compare with

  struct B : A {
  private:
    int foo();
  };

In this case, the call would certainly be invalid, even though your argument about casting B to an A would make it OK. Your argument basically says that an access adjustment to make something less accessible has no effect. That also doesn't sound right.

Steve Adamczyk: I agree that is strange. I do think that's what 11.8.3 [class.access.base] says, but perhaps that's not what we want it to say.




952. Insufficient description of “naming class”

Section: 11.8.3  [class.access.base]     Status: DRWP     Submitter: James Widman     Date: 7 August, 2009

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The access rules in 11.8.3 [class.access.base] do not appear to handle references in nested classes and outside of nonstatic member functions correctly. For example,

    struct A {
        typedef int I;    // public
    };
    struct B: private A { };
    struct C: B {
        void f() {
            I i1;         // error: access violation
        }
        I i2;             // OK
        struct D {
            I i3;         // OK
            void g() {
                I i4;     // OK
            }
        };
    };

The reason for this discrepancy is that the naming class in the reference to I is different in these cases. According to 11.8.3 [class.access.base] paragraph 5,

The access to a member is affected by the class in which the member is named. This naming class is the class in which the member name was looked up and found.

In the case of i1, the reference to I is subject to the transformation described in 11.4.3 [class.mfct.non.static] paragraph 3:

Similarly during name lookup, when an unqualified-id (7.5 [expr.prim]) used in the definition of a member function for class X resolves to a static member, an enumerator or a nested type of class X or of a base class of X, the unqualified-id is transformed into a qualified-id (7.5 [expr.prim]) in which the nested-name-specifier names the class of the member function.

As a result, the reference to I in the declaration of i1 is transformed to C::I, so that the naming class is C, and I is inacessible in C. In the remaining cases, however, the transformation does not apply. Thus, the naming class of I in these references is A, and I is publicly accessible in A.

Presumably either the definition of “naming class” must be changed or the transformation of unqualified-ids must be broadened to include all uses within the scope of a class and not just within nonstatic member functions (and following the declarator-id in the definition of a static member, per 11.4.9 [class.static] paragraph 4).




607. Lookup of mem-initializer-ids

Section: 11.9.3  [class.base.init]     Status: DRWP     Submitter: Richard Corden     Date: 5 December 2006

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

In an example like,

    struct Y {};

    template <typename T>
    struct X : public virtual Y { };

    template <typename T>
    class A : public X<T> {
      template <typename S>
      A (S)
        : S ()
      {
      }
    };

    template A<int>::A (Y);

Should S be found? (S is a dependent name, so if it resolves to a base class type in the instantiated template, it should satisfy the requirements.) All the compilers I tried allowed this example, but 11.9.3 [class.base.init] paragraph 2 says,

Names in a mem-initializer-id are looked up in the scope of the constructor's class and, if not found in that scope, are looked up in the scope containing the constructor's definition.

The name S is not declared in those scopes.

Mike Miller: Here's another example that is accepted by most/all compilers but not by the current wording:

    namespace N {
      struct B { B(int); };
      typedef B typedef_B;
      struct D: B {
        D();
      };
    }

    N::D::D(): typedef_B(0) { }

Except for the fact that the constructor function parameter names are ignored (see paragraph 7), what the compilers seem to be doing is essentially ordinary unqualified name lookup.

Notes from the October, 2009 meeting:

The eventual resolution of this issue should take into account the template parameter scope introduced by the resolution of issue 481.




2007. Argument-dependent lookup for operator=

Section: 12.2.2.3  [over.match.oper]     Status: DRWP     Submitter: Richard Smith     Date: 2014-09-23

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Consider an example like:

  template<typename T> struct A { typename T::error e; };
  template<typename T> struct B { };
  B<A<void>> b1, &b2 = (b1 = b1);

If the assignment operator performs argument-dependent lookup, A<void> will be an associated class and will be instantiated, producing an error. Similar questions apply to the other member-only overloaded operators, operator-> and operator[]. Bullet 3.2 of 12.2.2.3 [over.match.oper] should be changed not to perform unqualified lookup for these operators.




418. Imperfect wording on error on multiple default arguments on a called function

Section: 12.2.4  [over.match.best]     Status: DRWP     Submitter: Chris Bowler     Date: 27 May 2003

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 12.2.4 [over.match.best] paragraph 4, the following program appears to be ill-formed:

  void f(int, int=0);
  void f(int=0, int);

  void g() {
    f();
  }

Though I do not expect this is the intent of this paragraph in the standard.

12.2.4 [over.match.best] paragraph 4:

If the best viable function resolves to a function for which multiple declarations were found, and if at least two of these declarations or the declarations they refer to in the case of using-declarations specify a default argument that made the function viable, the program is ill-formed. [Example:
namespace A {
  extern "C" void f(int = 5);
}
namespace B {
  extern "C" void f(int = 5);
}
using A::f;
using B::f;
void use() {
f(3); //OK, default argument was not used for viability
f(); //Error: found default argument twice
}
end example]



110. Can template functions and classes be declared in the same scope?

Section: Clause 13  [temp]     Status: DRWP     Submitter: John Spicer     Date: 28 Apr 1999

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to Clause 13 [temp] paragraph 5,

Except that a function template can be overloaded either by (non-template) functions with the same name or by other function templates with the same name (13.10.4 [temp.over] ), a template name declared in namespace scope or in class scope shall be unique in that scope.
_N4868_.6.4.10 [basic.scope.hiding] paragraph 2 agrees that only functions, not function templates, can hide a class name declared in the same scope:
A class name (11.3 [class.name] ) or enumeration name (9.7.1 [dcl.enum] ) can be hidden by the name of an object, function, or enumerator declared in the same scope.
However, 6.4 [basic.scope] paragraph 4 treats functions and template functions together in this regard:
Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

John Spicer: You should be able to take an existing program and replace an existing function with a function template without breaking unrelated parts of the program. In addition, all of the compilers I tried allow this usage (EDG, Sun, egcs, Watcom, Microsoft, Borland). I would recommend that function templates be handled exactly like functions for purposes of name hiding.

Martin O'Riordan: I don't see any justification for extending the purview of what is decidedly a hack, just for the sake of consistency. In fact, I think we should go further and in the interest of consistency, we should deprecate the hack, scheduling its eventual removal from the C++ language standard.

The hack is there to allow old C programs and especially the 'stat.h' file to compile with minimum effort (also several other Posix and X headers). People changing such older programs have ample opportunity to "do it right". Indeed, if you are adding templates to an existing program, you should probably be placing your templates in a 'namespace', so the issue disappears anyway. The lookup rules should be able to provide the behaviour you need without further hacking.




1478. template keyword for dependent template template arguments

Section: 13.3  [temp.names]     Status: DRWP     Submitter: Johannes Schaub     Date: 2012-03-10

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 13.3 [temp.names] paragraph 4,

When the name of a member template specialization appears after . or -> in a postfix-expression or after a nested-name-specifier in a qualified-id, and the object expression of the postfix-expression is type-dependent or the nested-name-specifier in the qualified-id refers to a dependent type, but the name is not a member of the current instantiation (13.8.3.2 [temp.dep.type]), the member template name must be prefixed by the keyword template.

In other words, the template keyword is only required when forming a template-id. However, current compilers reject an example like:

  template<typename T, template<typename> class U = T::X> struct A;

and require the template keyword before X. Should the rule be amended to require the template keyword in cases like this?




1729. Matching declarations and definitions of variable templates

Section: 13.7  [temp.decls]     Status: DRWP     Submitter: Larisse Voufo     Date: 2013-08-05

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The relationship between declarations and definitions of variable templates is not clear. For example:

  template<typename T> auto var0 = T();  // #1a.
  template<typename T> extern T var0;    // #1b.

  template<typename T> T var1;           // #2a.
  template<typename T> extern auto var1; // #2b.
  template<typename T> extern T var1;    // #2c.
  template<typename T> T var1;           // #2d.

Questions:

  1. When is a variable template declaration a definition and when a non-defining declaration?

  2. What declarations are valid?

  3. Should auto declarations be allowed?

  4. To what extent, if any, do these involve type matching?

  5. How are types matched, especially in the presence of auto?

Proposed resolution (May, 2017):

This issue is resolved by the resolution of issue 1704.




2062. Class template redeclaration requirements

Section: 13.7.2  [temp.class]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-12-19

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

There does not appear to be a rule that two declarations of a class template must have compatible template parameter lists; e.g., it is not clear what makes the following ill-formed:

  template <typename> struct A;
  template <unsigned> struct A;



1896. Repeated alias templates

Section: 13.7.8  [temp.alias]     Status: DRWP     Submitter: Mike Miller     Date: 2014-03-18

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The current wording of the Standard does not permit repeated alias template declarations within a scope, but some current implementations allow it, presumably by analogy with typedef declarations. Should the Standard be changed to permit this usage?

Notes from the November, 2014 meeting:

CWG agreed that the usage should be permitted, provided that the dependent types are equivalent. Note that this is a weaker requirement than the token-for-token identity of the ODR, since alias templates are not definitions per Clause 13 [temp] paragraph 1.




2413. typename in conversion-function-ids

Section: 13.8  [temp.res]     Status: DRWP     Submitter: Davis Herring     Date: 2019-05-10

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The “Down with typename!” paper, P0634R3, overlooked the case of a conversion-type-id in a conversion-function-id:

  template<class T> struct S {
    operator typename T::X(); // typename is not helpful here.
  };

This context should be added to the list of contexts in which a qualified-id is assumed to name a type.




2461. Diagnosing non-bool type constraints

Section: 13.8  [temp.res]     Status: DRWP     Submitter: Hubert Tong     Date: 2020-04-20

[Accepted at the November, 2020 meeting.]

Given the following example,

  template <typename T> struct A {};
  template <typename T> void f() requires (sizeof(A<T>)) {}

the current wording does not appear to allow diagnosis of the program as ill-formed. In particular, 13.8 [temp.res] bullet 8.2 says,

The program is ill-formed, no diagnostic required, if:

However, substitution into the requires-clause in this case would result in a valid expression, but not one that is an atomic constraint that can be checked for satisfaction.

Proposed resolution (April, 2020):

Change bullet 8.2 of 13.8 [temp.res] as follows:

The program is ill-formed, no diagnostic required, if:




1841. < following template injected-class-name

Section: 13.8.2  [temp.local]     Status: DRWP     Submitter: Ismail Pazarbasi     Date: 2014-01-23

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 13.8.2 [temp.local]paragraph 1,

Like normal (non-template) classes, class templates have an injected-class-name (Clause 11 [class]). The injected-class-name can be used as a template-name or a type-name. When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type-specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.

The intent is that a < following such an injected-class-name is to be interpreted as the start of a template-argument-list (and an error if the following tokens do not constitute a valid template-argument-list), but that is not said explicitly.




1936. Dependent qualified-ids

Section: 13.8.3  [temp.dep]     Status: DRWP     Submitter: Richard Smith     Date: 2014-06-05

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The resolution of issue 1321 changed the term “dependent name” to apply only to unqualified-ids, presumably on the basis that only unqualified-ids affect the lookup set. However, the rule from 13.7.7.2 [temp.over.link] paragraph 5,

For determining whether two dependent names (13.8.3 [temp.dep]) are equivalent, only the name itself is considered, not the result of name lookup in the context of the template. If multiple declarations of the same function template differ in the result of this name lookup, the result for the first declaration is used.

should apply to non-dependent qualified-ids naming functions called with dependent arguments, as well.

There should also be a statement that the name of a member of an unknown specialization is a dependent name and so should fall under the rules of 13.8.4 [temp.dep.res] and not _N4868_.13.8.4 [temp.nondep].




1829. Dependent unnamed types

Section: 13.8.3.2  [temp.dep.type]     Status: DRWP     Submitter: Hubert Tong     Date: 2014-01-08

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The specification of dependent types in 13.8.3.2 [temp.dep.type] is given in terms of names. However, one might consider some unnamed types as dependent. Consider the following example:

  template <typename T> struct A {
    struct { } obj;
    void foo() {
      bar(obj); // lookup for bar when/where?
    }
  };

  void bar(...);

  int main() {
    A<int> a;
    a.foo();    // calls bar(...)?
  }

If the type of A::obj had a name, it would be dependent. However, the rationale for making nested types dependent is that they are subject to explicit specialization and thus not knowable at the point of the template definition. An unnamed type, as in this example, cannot be explicitly specialized and thus could be considered as a member of the current instantiation. Which treatment is intended?

Notes from the February, 2014 meeting:

There are other cases in which a named entity is dependnet, even though it cannot be explicitly specialized. CWG felt that the most consistent rule would be to make all nested classes dependent, whether named or not.




2065. Current instantiation of a partial specialization

Section: 13.8.3.2  [temp.dep.type]     Status: DRWP     Submitter: Richard Smith     Date: 2014-12-29

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

According to 13.8.3.2 [temp.dep.type] paragraph 1, a name refers to the current instantiation if it is

in the definition of a partial specialization or a member of a partial specialization, the name of the class template followed by the template argument list of the partial specialization enclosed in <> (or an equivalent template alias specialization).

I don't think this works. How are the argument lists compared? If it's using the “equivalent” rules, this doesn't work because we make no provision for “functionally equivalent but not equivalent” here. If it's using 13.6 [temp.type] paragraph 1, that fails because it doesn't handle dependent template arguments at all.

The same issue would come up when defining members of a partial specialization out-of-line.




2457. Unexpanded parameter packs don't make a function type dependent

Section: 13.8.3.2  [temp.dep.type]     Status: DRWP     Submitter: Richard Smith     Date: 2020-07-28

[Accepted at the November, 2020 meeting.]

Consider the following example:

  template<typename ...T> auto f() {
    using F = int(*)(int (...p)[sizeof(sizeof(T))]);
    // ...
  }

F is not covered in the list of cases in 13.8.3.2 [temp.dep.type] paragraph 9, because the types from which the function type is constructed are not dependent types. (The parameter pack p is of type int[sizeof(size_t)].) Similar situations arise with non-injective alias templates.

Proposed resolution (August, 2020):

Change 13.8.3.2 [temp.dep.type] paragraph 9 as follows:

A type is dependent if it is

(We do have the relevant wording for pack expansions in simple-template-ids in bullet 9.8, so that similar case is already handled.)




1028. Dependent names in non-defining declarations

Section: 13.8.4  [temp.dep.res]     Status: DRWP     Submitter: Sean Hunt     Date: 2010-02-03

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

The current wording of 13.8.4 [temp.dep.res] seems to assume that dependent names can only appear in the definition of a template:

In resolving dependent names, names from the following sources are considered:

However, dependent names can occur in non-defining declarations of the template as well; for instance,

    template<typename T>
    T foo(T, decltype(bar(T())));

bar needs to be looked up, even though there is no definition of foo in the translation unit.

Additional note (February, 2011):

The resolution of this issue can't simply replace the word “definition” with the word “declaration,” mutatis mutandis, because there can be multiple declarations in a translation unit (which isn't true of “the definition”). As a result, the issue was moved back to "open" status for further consideration.




1500. Name lookup of dependent conversion function

Section: 13.8.4.2  [temp.dep.candidate]     Status: DRWP     Submitter: Johannes Schaub     Date: 2012-04-27

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Consider the following example:

  template<typename T>
  struct A {
   operator int() { return 0; }

   void f() {
    operator T();
   }
  };

  int main() {
   A<int> a;
   a.f();
  }

One might expect this to call operator int when instantiating. But since operator T is a dependent name, it is looked up by unqualified lookup only in the definition context, where it will find no declaration. Argument-dependent lookup will not find anything in the instantiation context either, so this code is ill-formed. If we change operator int() to operator T(), which is a seemingly unrelated change, the code becomes well-formed.

There is implementation variability on this point.




271. Explicit instantiation and template argument deduction

Section: 13.10.3  [temp.deduct]     Status: DRWP     Submitter: John Spicer     Date: 20 Feb 2001

[Accepted at the November, 2020 meeting as part of paper P1787R6 and moved to DR at the February, 2021 meeting.]

Nicolai Josuttis sent me an example like the following:

    template <typename RET, typename T1, typename T2>
    const RET& min (const T1& a, const T2& b)
    {
	return (a < b ? a : b);
    }
    template const int& min<int>(const int&,const int&);  // #1
    template const int& min(const int&,const int&);       // #2

Among the questions was whether explicit instantiation #2 is valid, where deduction is required to determine the type of RET.

The first thing I realized when researching this is that the standard does not really spell out the rules for deduction in declarative contexts (friend declarations, explicit specializations, and explicit instantiations). For explicit instantiations, 13.9.3 [temp.explicit] paragraph 2 does mention deduction, but it doesn't say which set of deduction rules from 13.10.3 [temp.deduct] should be applied.

Second, Nicolai pointed out that 13.9.3 [temp.explicit] paragraph 6 says

A trailing template-argument can be left unspecified in an explicit instantiation provided it can be deduced from the type of a function parameter (13.10.3 [temp.deduct]).

This prohibits cases like #2, but I believe this was not considered in the wording as there is no reason not to include the return type in the deduction process.

I think there may have been some confusion because the return type is excluded when doing deduction on a function call. But there are contexts where the return type is included in deduction, for example, when taking the address of a function template specialization.

Suggested resolution:

  1. Update 13.10.3 [temp.deduct] to include a section "Deducing template arguments from a declaration" that describes how deduction is done when finding a template that matches a declaration. This should, I believe, include the return type.
  2. Update 13.9.3 [temp.explicit] to make reference to the new rules in 13.10.3 [temp.deduct] and remove the description of the deduction details from 13.9.3 [temp.explicit] paragraph 6.



1724. Unclear rules for deduction failure

Section: 13.10.3  [temp.deduct]     Status: DRWP     Submitter: James Widman     Date: 2013-07-31

[Accepted as a DR at the October, 2021 meeting.]

According to 13.10.3 [temp.deduct] paragraph 8,

If a substitution results in an invalid type or expression, type deduction fails. An invalid type or expression is one that would be ill-formed, with a diagnostic required, if written using the substituted arguments.

Presumably the phrase “if written” refers to rewriting the template declaration in situ with the substituted arguments, rather than writing that type or expression at some arbitrary location, e.g.,

  void g(double) = delete;

  template<class T> auto f(T t) -> decltype(g(t));

  void g(int);

  void h() {
    typedef int T;
    T t = 42;
    g(t);  // Ok (I “wrote the substituted arguments”, and it seems fine)
    f(42); // Presumably substitution is meant to fail.
  }

Perhaps a clearer formulation could be used?

Proposed resolution (August, 2021):

Change 13.10.3.1 [temp.deduct.general] paragraph 8 as follows:

If a substitution results in an invalid type or expression, type deduction fails. An invalid type or expression is one that would be ill-formed, with a diagnostic required, if written in the same context using the substituted arguments.



2369. Ordering between constraints and substitution

Section: 13.10.3  [temp.deduct]     Status: DRWP     Submitter: Agustin Bergé     Date: 2017-10-09

[Accepted at the November, 2020 meeting.]

The specification of template argument deduction in 13.10.3 [temp.deduct] paragraph 5 specifies the order of processing as:

  1. substitute explicitly-specified template arguments throughout the template parameter list and type;

  2. deduce template arguments from the resulting function signature;

  3. check that non-dependent parameters can be initialized from their arguments;

  4. substitute deduced template arguments into the template parameter list and particularly into any needed default arguments to form a complete template argument list;;

  5. substitute resulting template arguments throughout the type;

  6. check that the associated constraints are satisfied;

  7. check that remaining parameters can be initialized from their arguments.

This ordering yields unexpected differences between concept and SFINAE implementations. For example:

   template <typename T>
   struct static_assert_integral {
     static_assert(std::is_integral_v<T>);
     using type = T;
   };

   struct fun {
     template <typename T,
       typename Requires = std::enable_if_t<std::is_integral_v<T>>>
       typename static_assert_integral<T>::type
     operator()(T) {}
   };

Here the substitution ordering guarantees are leveraged to prevent static_assert_integral<T> from being instantiated when the constraints are not satisfied. As a result, the following assertion holds:

   static_assert(!std::is_invocable_v<fun, float>);

A version of this code written using constraints unexpectedly behaves differently:

   struct fun {
     template <typename T>
       requires std::is_integral_v<T>
     typename static_assert_integral<T>::type
     operator()(T) {}
   };

or

   struct fun {
     template <typename T>
     typename static_assert_integral<T>::type
     operator()(T) requires std::is_integral_v<T> {}
   };

   static_assert(!std::is_invocable_v<fun, float>); // error: static assertion failed: std::is_integral_v<T>

Perhaps steps 5 and 6 should be interchanged.

Proposed resolution (August, 2020):

  1. Delete paragraph 10 of 13.10.3.2 [temp.deduct.call]:

  2. If deduction succeeds for all parameters that contain template-parameters that participate in template argument deduction, and all template arguments are explicitly specified, deduced, or obtained from default template arguments, remaining parameters are then compared with the corresponding arguments. For each remaining parameter P with a type that was non-dependent before substitution of any explicitly-specified template arguments, if the corresponding argument A cannot be implicitly converted to P, deduction fails. [Note 2: Parameters with dependent types in which no template-parameters participate in template argument deduction, and parameters that became non-dependent due to substitution of explicitly-specified template arguments, will be checked during overload resolution. —end note]

    [Example 9:

      template <class T> struct Z {
        typedef typename T::x xx;
      };
      template <class T> typename Z<T>::xx f(void *, T); // #1
      template <class T> void f(int, T);                 // #2
      struct A {} a;
      int main() {
        f(1, a);   // OK, deduction fails for #1 because there is no conversion from int to void*
      }
    

    end example]

  3. Change 13.10.3.1 [temp.deduct.general] paragraph 5 as follows:

  4. ...When all template arguments have been deduced or obtained from default template arguments, all uses of template parameters in the template parameter list of the template and the function type are replaced with the corresponding deduced or default argument values. If the substitution results in an invalid type, as described above, type deduction fails. If the function template has associated constraints (13.5.3 [temp.constr.decl]), those constraints are checked for satisfaction (13.5.2 [temp.constr.constr]). If the constraints are not satisfied, type deduction fails. In the context of a function call, if type deduction has not yet failed, then for those function parameters for which the function call has arguments, each function parameter with a type that was non-dependent before substitution of any explicitly-specified template arguments is checked against its corresponding argument; if the corresponding argument cannot be implicitly converted to the parameter type, type deduction fails. [Note: Overload resolution will check the other parameters, including parameters with dependent types in which no template parameters participate in template argument deduction and parameters that became non-dependent due to substitution of explicitly-specified template arguments. —end note] If type deduction has not yet failed, then all uses of template parameters in the function type are replaced with the corresponding deduced or default argument values. If the substitution results in an invalid type, as described above, type deduction fails. [Example:

      template <class T> struct Z {
        typedef typename T::x xx;
      };
      template <class T> concept C = requires { typename T::A; };
      template <C T> typename Z<T>::xx f(void *, T); // #1
      template <class T> void f(int, T);             // #2
      struct A {} a;
      struct ZZ {
        template <class T, class = typename Z<T>::xx> operator T *();
        operator int();
      };
      int main() {
        ZZ zz;
        f(1, a);   // OK, deduction fails for #1 because there is no conversion from int to void*
        f(zz, 42); // OK, deduction fails for #1 because C<int> is not satisfied
      }
    

    end example]






Issues with "WP" Status


2455. Concatenation of string literals vs translation phases 5 and 6

Section: 5.2  [lex.phases]     Status: WP     Submitter: Tom Honermann     Date: 2020-07-02

[Addressed by paper P2314R4, adopted at the October, 2021 plenary.]

According to 5.2 [lex.phases] paragraph 1, concatenation of adjacent string literals is performed in translation phase 6, after conversion of the literal values to the execution character set. However, 5.13.5 [lex.string] paragraph 11 indicates that the interpretation of the string contents is dependent on the encoding-prefixes specified for the literals being concatenated:

In translation phase 6 (5.2 [lex.phases]), adjacent string-literals are concatenated. If both string-literals have the same encoding-prefix, the resulting concatenated string-literal has that encoding-prefix. If one string-literal has no encoding-prefix, it is treated as a string-literal of the same encoding-prefix as the other operand. If a UTF-8 string literal token is adjacent to a wide string literal token, the program is ill-formed. Any other concatenations are conditionally-supported with implementation-defined behavior. [Note: This concatenation is an interpretation, not a conversion. Because the interpretation happens in translation phase 6 (after each character from a string-literal has been translated into a value from the appropriate character set), a string-literal's initial rawness has no effect on the interpretation or well-formedness of the concatenation. —end note]

This seems to indicate that string-literals with different encoding-prefixes are separately converted and then joined, potentially resulting in strings containing code unit sequences corresponding to different character encodings. This reading would contradict the intent, expressed in adjacent table, that, e.g., u"a" "b" means the same as u"ab".

There is implementation divergence in the handling of this specification.

Phases 5 and 6 cannot simply be reversed, because interpretation of escape sequences must precede concatenation, as specified later in the same paragraph:

Characters in concatenated strings are kept distinct.

[Example:

"\xA" "B"

contains the two characters '\xA' and 'B' after concatenation (and not the single hexadecimal character '\xAB'). —end example]

Richard Smith suggested here that "we should remove phases 5 and 6 entirely, parse one or more string-literal tokens as a string literal expression, and only perform the translation from the contents of the string literal tokens into characters in the execution character set as part of specifying the semantics of a string literal expression."




1972. Identifier character restrictions in non-identifiers

Section: 5.10  [lex.name]     Status: WP     Submitter: Richard Smith     Date: 2014-07-15

[Accepted at the June, 2021 meeting as part of paper P1949R7 (C++ Identifier Syntax using Unicode Standard Annex 31).]

According to 5.10 [lex.name] paragraph 1,

Each universal-character-name in an identifier shall designate a character whose encoding in ISO 10646 falls into one of the ranges specified in _N4606_.E.1 [charname.allowed].

However, identifier-nondigit is also used in the grammar for pp-number. Should this restriction also be understood to apply in that non-identifier context?




1656. Encoding of numerically-escaped characters

Section: 5.13.3  [lex.ccon]     Status: WP     Submitter: Mike Miller     Date: 2013-04-30

[Accepted at the November, 2020 meeting as part of paper P2029R4.]

According to 5.13.3 [lex.ccon] paragraph 4,

The escape \ooo consists of the backslash followed by one, two, or three octal digits that are taken to specify the value of the desired character. The escape \xhhh consists of the backslash followed by x followed by one or more hexadecimal digits that are taken to specify the value of the desired character. There is no limit to the number of digits in a hexadecimal sequence. A sequence of octal or hexadecimal digits is terminated by the first character that is not an octal digit or a hexadecimal digit, respectively. The value of a character literal is implementation-defined if it falls outside of the implementation-defined range defined for char (for literals with no prefix), char16_t (for literals prefixed by 'u'), char32_t (for literals prefixed by 'U'), or wchar_t (for literals prefixed by 'L').

It is not clearly stated whether the “desired character” being specified reflects the source or the target encoding. This particularly affects UTF-8 string literals (5.13.5 [lex.string] paragraph 7) :

A string literal that begins with u8, such as u8"asdf", is a UTF-8 string literal and is initialized with the given characters as encoded in UTF-8.

For example, assuming the source encoding is Latin-1, is u8"\xff" supposed to specify a three-byte string whose first two bytes are 0xc3 0xbf (the UTF-8 encoding of \u00ff) or a two-byte string whose first byte has the value 0xff? (At least some current implementations assume the latter interpretation.)

Notes from the September, 2013 meeting:

The second interpretation (that the escape sequence specifies the execution-time code unit) is intended.




2333. Escape sequences in UTF-8 character literals

Section: 5.13.3  [lex.ccon]     Status: WP     Submitter: Mike Miller     Date: 2017-01-05

[Accepted at the November, 2020 meeting as part of paper P2029R4.]

The meaning of a numeric escape appearing in a UTF-8 character literal is not clear. 5.13.3 [lex.ccon] paragraph 3 assumes that the contents of the quoted string is a character with an ISO 10646 code point value, which is not necessarily the case with a numeric escape, and paragraph 8 could be read to indicate that a numeric escape specifies the actual runtime value of the object rather than a Unicode code point. In addition, paragraph 8 only specifies the result for unprefixed and wide-character literals, not for UTF-8 literals, so that could be read as indicating that a numeric escape in a UTF-8 character literal is undefined behavior (i.e., not defined by the Standard).

Notes from the August, 2017 teleconference:

An escape sequence in a UTF-8 character literal should be ill-formed.




2402. When is the restriction to a single c-char in a Unicode literal enforced?

Section: 5.13.3  [lex.ccon]     Status: WP     Submitter: Richard Smith     Date: 2019-01-08

[Adopted at the November, 2020 meeting as part of paper P2029R4.]

According to 5.13.3 [lex.ccon] paragraphs 3-5, a Unicode character literal “containing multiple c-chars is ill-formed.” However, it is not clear in what phase of translation that restriction applies.

One possible resolution would be to add a note saying that the pp-token is formed according to the grammar and the restriction to a single c-char is checked in phase 7.




411. Use of universal-character-name in character versus string literals

Section: 5.13.5  [lex.string]     Status: WP     Submitter: James Kanze     Date: 23 Apr 2003

[Accepted at the November, 2020 meeting as part of paper P2029R4.]

5.13.5 [lex.string] paragraph 5 reads

Escape sequences and universal-character-names in string literals have the same meaning as in character literals, except that the single quote ' is representable either by itself or by the escape sequence \', and the double quote " shall be preceded by a \. In a narrow string literal, a universal-character-name may map to more than one char element due to multibyte encoding.

The first sentence refers us to 5.13.3 [lex.ccon], where we read in the first paragraph that "An ordinary character literal that contains a single c-char has type char [...]." Since the grammar shows that a universal-character-name is a c-char, something like '\u1234' must have type char (and thus be a single char element); in paragraph 5, we read that "A universal-character-name is translated to the encoding, in the execution character set, of the character named. If there is no such encoding, the universal-character-name is translated to an implemenation-defined encoding."

This is in obvious contradiction with the second sentence. In addition, I'm not really clear what is supposed to happen in the case where the execution (narrow-)character set is UTF-8. Consider the character \u0153 (the oe in the French word oeuvre). Should '\u0153' be a char, with an "error" value, say '?' (in conformance with the requirement that it be a single char), or an int, with the two char values 0xC5, 0x93, in an implementation defined order (in conformance with the requirement that a character representable in the execution character set be represented). Supposing the former, should "\u0153" be the equivalent of "?" (in conformance with the first sentence), or "\xC5\x93" (in conformance with the second).

Notes from October 2003 meeting:

We decided we should forward this to the C committee and let them resolve it. Sent via e-mail to John Benito on November 14, 2003.

Reply from John Benito:

I talked this over with the C project editor, we believe this was handled by the C committee before publication of the current standard.

WG14 decided there needed to be a more restrictive rule for one-to-one mappings: rather than saying "a single c-char" as C++ does, the C standard says "a single character that maps to a single-byte execution character"; WG14 fully expect some (if not many or even most) UCNs to map to multiple characters.

Because of the fundamental differences between C and C++ character types, I am not sure the C committee is qualified to answer this satisfactorily for WG21. WG14 is willing to review any decision reached for compatibility.

I hope this helps.

(See also issue 912 for a related question.)




2502. Unintended declaration conflicts in nested statement scopes

Section: 6.4.3  [basic.scope.block]     Status: WP     Submitter: Jens Maurer     Date: 2021-08-26

[Accepted at the February, 2022 meeting.]

The changes of P1787R6 inadvertently made constructs like

  if (int a = 1)
    if (int a = 1)
      ...

ill-formed.

Proposed resolution (September, 2021):

Change 6.4.3 [basic.scope.block] bullet 2.2 as follows:

If a declaration whose target scope is the block scope S of a

potentially conflicts with a declaration whose target scope is the parent scope of S, the program is ill-formed.

(See editorial issue 4843.)




2121. More flexible lambda syntax

Section: 7.5.5.1  [expr.prim.lambda.general]     Status: WP     Submitter: EWG     Date: 2015-05-06

[Adopted at the February, 2021 meeting as paper P1102R2.]

The grammar in 7.5.5 [expr.prim.lambda] paragraph 1 allows for omitting the the parameter list but only for a non-mutable lambda, i.e., it does not permit

    auto lambda = [] mutable { };

This should be addressed, and the possibility of other abbreviated forms should be considered, such as:

    [] -> float { return 42; }
    [] noexcept { foo(); }

(This is EWG issue 135.)

Proposed resolution (May, 2015):

  1. Change the grammar in 7.5.5 [expr.prim.lambda] paragraph 1 as follows:

  2. Change 7.5.5 [expr.prim.lambda] paragraph 4 as follows:

  3. If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). The lambda return type...
  4. Change 7.5.5 [expr.prim.lambda] paragraph 5 as follows:

  5. The closure type for a non-generic lambda-expression has a public inline function call operator (12.4.4 [over.call]) whose parameters and return type are described by the lambda-expression's parameter-declaration-clause and trailing-return-type respectively. For a generic lambda... This function call operator or operator template is declared const (11.4.3 [class.mfct.non.static]) if and only if the lambda-expression's parameter-declaration-clause is not followed by lambda-declarator does not contain the keyword mutable. It is neither...

Notes from the October, 2015 meeting:

Additional wording is needed in the proposed resolution in paragraph 5 to handle the potential absence of the parameter declaration clause.




1711. Missing specification of variable template partial specializations

Section: 13.7.6  [temp.spec.partial]     Status: WP     Submitter: Richard Smith     Date: 2013-07-08

[Accepted at the November, 2020 meeting as paper P2096R2.]

It appears that partial specializations of variable templates are intended to be supported, as 13.4.4 [temp.arg.template] paragraph 2 says,

Any partial specializations (13.7.6 [temp.spec.partial]) associated with the primary class template or primary variable template are considered when a specialization based on the template template-parameter is instantiated.

However, there is no explicit specification for how they are to be handled, and the wording in 13.7.6 [temp.spec.partial] and its subsections explicitly applies only to partial specializations of class templates.

Additional note, July, 2017:

The term “primary template” appears not to be defined in the current wording; the resolution of this issue might be a good opportunity to add such a definition.




2482. bit_cast and indeterminate values

Section: 22.15.3  [bit.cast]     Status: WP     Submitter: Richard Smith     Date: 2019-06-20

[Resolved by paper P1272R4, adopted at the October, 2021 plenary.]

As currently specified, bit_cast from an indeterminate value produces an unspecified value rather than an indeterminate value. That means this can't be implemented by a simple load on some implementations, and instead will require some kind of removing-the-taint-of-an-uninitialized-value operation to be performed. (A similar concern applies to reading from padding bits.)

The intent is as follows:

Some examples:

  struct A { char c; /* char padding : 8; */ short s; };
  struct B { char x[4]; };

  B one() {
    A a = {1, 2};
    return std::bit_cast<B>(a);
  }

In one(), the second byte of the object representation of a is bad. That means that the second byte of the produced B object is bad, so x[1] in the produced B object is an indeterminate value. The above function, if declared constexpr, would be usable in constant expressions so long as you don't look at one().x[1].

  A two() {
    B b;
    b.x[0] = 'a';
    b.x[2] = 1;
    b.x[3] = 2;
    return std::bit_cast<A>(b);
  }

In two() , the second byte of the object representation of b is bad. But a bit_cast to A doesn't care because it never looks at that byte. The above function returns an A with a fully-defined value. If declared constexpr, it would produce a normal, fully-initialized value.

  int three() {
    int n;
    return std::bit_cast<int>(n);
  }

In three(), the entirety of n is bad. A bit_cast from it produces an int whose value is indeterminate. And because we have an expression of non-byte-like type that produced an indeterminate value, the behavior is undefined.

  B four() {
    int n;
    return std::bit_cast<B>(n);
  }

In four(), just like three(), the entirety of n is bad, so the scalar subobjects of B are bad too. But because they're of byte-like type, that's OK: we can copy them about and produce them from prvalue expressions.

Proposed resolution (May, 2021):

Change 22.15.3 [bit.cast] paragraph 2 as follows:

Returns: An object of type To. Implicitly creates objects nested within the result (6.7.2 [intro.object]). Each bit of the value representation of the result is equal to the corresponding bit in the object representation of from. Padding bits of the result are unspecified. For the result and each object created within it, if there is no value of the object's type corresponding to the value representation produced, the behavior is undefined. If there are multiple such values, which value is produced is unspecified. A bit in the value representation of the result is indeterminate if it does not correspond to a bit in the value representation of from or corresponds to a bit of an object that is not within its lifetime or has an indeterminate value (6.7.4 [basic.indet]). For each bit in the value representation of the result that is indeterminate, the smallest object containing that bit has an indeterminate value; the behavior is undefined unless that object is of unsigned ordinary character type or std::byte type. The result does not otherwise contain any indeterminate values.





Issues with "CD1" Status


663. Valid Cyrillic identifier characters

Section: _N2691_.E  [extendid]     Status: CD1     Submitter: Steve Clamage     Date: 30 November 2007

[Voted into the WP at the June, 2008 meeting.]

The C99 and C++ Standards disagree about the validity of two Cyrillic characters for use in identifiers. C++ (_N2691_.E [extendid]) says that 040d is valid in an identifier but that 040e is not; C99 (Annex D) says exactly the opposite. In fact, both characters should be accepted in identifiers; see the Unicode chart.

Proposed resolution (February, 2008):

The reference in paragraph 2 should be changed to ISO/IEC TR 10176:2003 and the table should be changed to conform to the one in that document (beginning on page 34).




122. template-ids as unqualified-ids

Section: _N4567_.5.1.1  [expr.prim.general]     Status: CD1     Submitter: Mike Miller     Date: 3 June 1999

[Moved to DR at 10/01 meeting.]

_N4567_.5.1.1 [expr.prim.general] paragraph 11 reads,

A template-id shall be used as an unqualified-id only as specified in 13.9.3 [temp.explicit] , 13.9 [temp.spec] , and 13.7.6 [temp.spec.partial] .

What uses of template-ids as unqualified-ids is this supposed to prevent? And is the list of referenced sections correct/complete? For instance, what about 13.10.2 [temp.arg.explicit], "Explicit template argument specification?" Does its absence from the list in _N4567_.5.1.1 [expr.prim.general] paragraph 11 mean that "f<int>()" is ill-formed?

This is even more confusing when you recall that unqualified-ids are contained in qualified-ids:

qualified-id: ::opt nested-name-specifier templateopt unqualified-id

Is the wording intending to say "used as an unqualified-id that is not part of a qualified-id?" Or something else?

Proposed resolution (10/00):

Remove the referenced sentence altogether.




125. Ambiguity in friend declaration syntax

Section: _N4567_.5.1.1  [expr.prim.general]     Status: CD1     Submitter: Martin von Loewis     Date: 7 June 1999

[Voted into WP at March 2004 meeting.]

The example below is ambiguous.

    struct A{
      struct B{};
    };

    A::B C();

    namespace B{
      A C();
    }

    struct Test {
      friend A::B ::C();
    };
Here, it is not clear whether the friend declaration denotes A B::C() or A::B C(), yet the standard does not resolve this ambiguity.

The ambiguity arises since both the simple-type-specifier (9.2.9.3 [dcl.type.simple] paragra 1) and an init-declararator (9.3 [dcl.decl] paragraph 1) contain an optional :: and an optional nested-name-specifier (_N4567_.5.1.1 [expr.prim.general] paragraph 1) . Therefore, two different ways to analyse this code are possible:

simple-type-specifier = A::B
init-declarator = ::C()
simple-declaration = friend A::B ::C();
or
simple-type-specifier = A
init-declarator = ::B::C()
simple-declaration = friend A ::B::C();
Since it is a friend declaration, the init-declarator may be qualified, and start with a global scope.

Suggested Resolution: In the definition of nested-name-specifier, add a sentence saying that a :: token immediately following a nested-name-specifier is always considered as part of the nested-name-specifier. Under this interpretation, the example is ill-formed, and should be corrected as either

    friend A (::B::C)();   //or
    friend A::B (::C)();

An alternate suggestion — changing 9.2 [dcl.spec] to say that

The longest sequence of tokens that could possibly be a type name is taken as the decl-specifier-seq of a declaration.

— is undesirable because it would make the example well-formed rather than requiring the user to disambiguate the declaration explicitly.

Proposed resolution (04/01):

(See below for problem with this, from 10/01 meeting.)

In _N4567_.5.1.1 [expr.prim.general] paragraph 7,

  1. Before the grammar for qualified-id, start a new paragraph 7a with the text

    A qualified-id is an id-expression that contains the scope resolution operator ::.
  2. Following the grammar fragment, insert the following:

    The longest sequence of tokens that could form a qualified-id constitutes a single qualified-id. [Example:

        // classes C, D; functions F, G, namespace N; non-class type T
        friend C ::D::F();   // ill-formed, means friend (C::D::F)();
        friend C (::D::F)(); // well-formed
        friend N::T ::G();   // ill-formed, means friend (N::T::G)();
        friend N::T (::G)(); // well-formed
    

    end example]

  3. Start a new paragraph 7b following the example.

(This resolution depends on that of issue 215.)

Notes from 10/01 meeting:

It was pointed out that the proposed resolution does not deal with cases like X::Y where X is a type but not a class type. The working group reaffirmed its decision that the disambiguation should be syntactic only, i.e., it should depend only on whether or not the name is a type.

Jason Merrill :

At the Seattle meeting, I suggested that a solution might be to change the class-or-namespace-name in the nested-name-specifier rule to just be "identifier"; there was some resistance to this idea. FWIW, I've tried this in g++. I had to revise the idea so that only the second and subsequent names were open to being any identifier, but that seems to work just fine.

So, instead of

it would be

Or some equivalent but right-associative formulation, if people feel that's important, but it seems irrelevant to me.

Clark Nelson :

Personally, I prefer the left-associative rule. I think it makes it easier to understand. I was thinking about this production a lot at the meeting, considering also some issues related to 301. My formulation was getting kind of ugly, but with a left-associative rule, it gets a lot nicer.

Your proposal isn't complete, however, as it doesn't allow template arguments without an explicit template keyword. You probably want to add an alternative for:

There is admittedly overlap between this alternative and

but I think they're both necessary.

Notes from the 4/02 meeting:

The changes look good. Clark Nelson will merge the two proposals to produce a single proposed resolution.

Proposed resolution (April 2003):

nested-name-specifier is currently defined in _N4567_.5.1.1 [expr.prim.general] paragraph 7 as:

The proposed definition is instead:

Issue 215 is addressed by using type-name instead of class-name in the first alternative. Issue 125 (this issue) is addressed by using identifier instead of anything more specific in the third alternative. Using left association instead of right association helps eliminate the need for class-or-namespace-name (or type-or-namespace-name, as suggested for issue 215).

It should be noted that this formulation also rules out the possibility of A::template B::, i.e. using the template keyword without any template arguments. I think this is according to the purpose of the template keyword, and that the former rule allowed such a construct only because of the difficulty of formulation of a right-associative rule that would disallow it. But I wanted to be sure to point out this implication.

Notes from April 2003 meeting:

See also issue 96.

The proposed change resolves only part of issue 215.




466. cv-qualifiers on pseudo-destructor type

Section: _N4778_.7.6.1.4  [expr.pseudo]     Status: CD1     Submitter: Mark Mitchell     Date: 18 Mar 2004

[Voted into WP at April, 2006 meeting.]

_N4778_.7.6.1.4 [expr.pseudo] paragraph 2 says both:

The type designated by the pseudo-destructor-name shall be the same as the object type.
and also:
The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type.
Which is it? "The same" or "the same up to cv-qualifiers"? The second sentence is more generous than the first. Most compilers seem to implement the less restrictive form, so I guess that's what I think we should do.

See also issues 305 and 399.

Proposed resolution (October, 2005):

Change _N4778_.7.6.1.4 [expr.pseudo] paragraph 2 as follows:

The left-hand side of the dot operator shall be of scalar type. The left-hand side of the arrow operator shall be of pointer to scalar type. This scalar type is the object type. The type designated by the pseudo-destructor-name shall be the same as the object type. The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type. Furthermore, the two type-names in a pseudo-destructor-name of the form shall designate the same scalar type. The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type.



141. Non-member function templates in member access expressions

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: CD1     Submitter: fvali     Date: 31 July 1999

[Voted into the WP at the June, 2008 meeting.]

_N4868_.6.5.6 [basic.lookup.classref] paragraph 1 says,

In a class member access expression (7.6.1.5 [expr.ref] ), if the . or -> token is immediately followed by an identifier followed by a <, the identifier must be looked up to determine whether the < is the beginning of a template argument list (13.3 [temp.names] ) or a less-than operator. The identifier is first looked up in the class of the object expression. If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class or function template.

There do not seem to be any circumstances in which use of a non-member template function would be well-formed as the id-expression of a class member access expression.

Proposed Resolution (November, 2006):

Change _N4868_.6.5.6 [basic.lookup.classref] paragraph 1 as follows:

In a class member access expression (7.6.1.5 [expr.ref]), if the . or -> token is immediately followed by an identifier followed by a <, the identifier must be looked up to determine whether the < is the beginning of a template argument list (13.3 [temp.names]) or a less-than operator. The identifier is first looked up in the class of the object expression. If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class or function template...



305. Name lookup in destructor call

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: CD1     Submitter: Mark Mitchell     Date: 19 May 2001

[Voted into WP at the October, 2006 meeting.]

I believe this program is invalid:

    struct A {
    };

    struct C {
      struct A {};
      void f ();
    };

    void C::f () {
      ::A *a;
      a->~A ();
    }
The problem is that _N4868_.6.5.6 [basic.lookup.classref] says that you have to look up A in both the context of the pointed-to-type (i.e., ::A), and in the context of the postfix-expression (i.e., the body of C::f), and that if the name is found in both places it must name the same type in both places.

The EDG front end does not issue an error about this program, though.

Am I reading the standardese incorrectly?

John Spicer: I think you are reading it correctly. I think I've been hoping that this would get changed. Unlike other dual lookup contexts, this is one in which the compiler already knows the right answer (the type must match that of the left hand of the -> operator). So I think that if either of the types found matches the one required, it should be sufficient. You can't say a->~::A(), which means you are forced to say a->::A::~A(), which disables the virtual mechanism. So you would have to do something like create a local typedef for the desired type.

See also issues 244, 399, and 466.

Proposed resolution (April, 2006):

  1. Remove the indicated text from _N4868_.6.5.6 [basic.lookup.classref] paragraph 2:

    If the id-expression in a class member access (7.6.1.5 [expr.ref]) is an unqualified-id, and the type of the object expression is of a class type C (or of pointer to a class type C), the unqualified-id is looked up in the scope of class C...
  2. Change _N4868_.6.5.6 [basic.lookup.classref] paragraph 3 as indicated:

    If the unqualified-id is ~type-name, the type-name is looked up in the context of the entire postfix-expression. and If the type T of the object expression is of a class type C (or of pointer to a class type C), the type-name is also looked up in the context of the entire postfix-expression and in the scope of class C. The type-name shall refer to a class-name. If type-name is found in both contexts, the name shall refer to the same class type. If the type of the object expression is of scalar type, the type-name is looked up in the scope of the complete postfix-expression. At least one of the lookups shall find a name that refers to (possibly cv-qualified) T. [Example:
    
        struct A { };
    
        struct B {
          struct A { };
          void f(::A* a);
        };
    
        void B::f(::A* a) {
          a->~A();  // OK, lookup in *a finds the injected-class-name
        }
    
    end example]

[Note: this change also resolves issue 414.]




381. Incorrect example of base class member lookup

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: CD1     Submitter: Steve Adamczyk     Date: 8 Nov 2002

[Voted into WP at October 2004 meeting.]

The example in _N4868_.6.5.6 [basic.lookup.classref] paragraph 4 is wrong (see 11.8.3 [class.access.base] paragraph 5; the cast to the naming class can't be done) and needs to be corrected. This was noted when the final version of the algorithm for issue 39 was checked against it.

Proposed Resolution (October 2003):

Remove the entire note at the end of _N4868_.6.5.6 [basic.lookup.classref] paragraph 4, including the entire example.




414. Multiple types found on destructor lookup

Section: _N4868_.6.5.6  [basic.lookup.classref]     Status: CD1     Submitter: John Spicer     Date: 1 May 2003

[Voted into WP at the October, 2006 meeting.]

By _N4868_.6.5.6 [basic.lookup.classref] paragraph 3, the following is ill-formed because the two lookups of the destructor name (in the scope of the class of the object and in the surrounding context) find different Xs:

  struct X {};
  int main() {
    X x;
    struct X {};
    x.~X();  // Error?
  }

This is silly, because the compiler knows what the type has to be, and one of the things found matches that. The lookup should require only that one of the lookups finds the required class type.

Proposed resolution (April, 2005):

This issue is resolved by the resolution of issue 305.




452. Wording nit on description of this

Section: _N4868_.11.4.3.2  [class.this]     Status: CD1     Submitter: Gennaro Prota     Date: 8 Jan 2004

[Voted into WP at July, 2007 meeting.]

_N4868_.11.4.3.2 [class.this] paragraph 1, which specifies the meaning of the keyword 'this', seems to limit its usage to the *body* of non-static member functions. However 'this' is also usable in ctor-initializers which, according to the grammar in 9.5 [dcl.fct.def] par. 1, are not part of the body.

Proposed resolution: Changing the first part of _N4868_.11.4.3.2 [class.this] par. 1 to:

In the body of a nonstatic (9.3) member function or in a ctor-initializer (12.6.2), the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called.

NOTE: I'm talking of constructors as functions that are "called"; there have been discussions on c.l.c++.m as to whether constructors are "functions" and to whether this terminology is correct or not; I think it is both intuitive and in agreement with the standard wording.

Steve Adamczyk: See also issue 397, which is defining a new syntax term for the body of a function including the ctor-initializers.

Notes from the March 2004 meeting:

This will be resolved when issue 397 is resolved.

Proposed resolution (October, 2005):

  1. Change 9.5 [dcl.fct.def] paragraph 1 as indicated:

  2. Function definitions have the form

    An informal reference to the body of a function should be interpreted as a reference to the nonterminal function-body.

  3. Change the definition of function-try-block in Clause 14 [except] paragraph 1:

  4. Change 6.4.6 [basic.scope.class] paragraph 1, point 1, as indicated:

  5. The potential scope of a name declared in a class consists not only of the declarative region following the name's point of declaration, but also of all function bodies, bodies and default arguments, and constructor ctor-initializers in that class (including such things in nested classes).
  6. Change 6.4.6 [basic.scope.class] paragraph 1, point 5, as indicated:

  7. The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, member function definitions (including the member function body and, for constructor functions (11.4.5 [class.ctor]), the ctor-initializer (11.9.3 [class.base.init])) and any portion of the declarator part of such definitions which follows the identifier, including a parameter-declaration-clause and any default arguments (9.3.4.7 [dcl.fct.default]). [Example:...
  8. Change footnote 32 in 6.5.3 [basic.lookup.unqual] paragraph 8 as indicated:

  9. That is, an unqualified name that occurs, for instance, in a type or default argument expression in the parameter-declaration-clause, parameter-declaration-clause or in the function body, or in an expression of a mem-initializer in a constructor definition.
  10. Change _N4567_.5.1.1 [expr.prim.general] paragraph 3 as indicated:

  11. ...The keyword this shall be used only inside a non-static class member function body (11.4.2 [class.mfct]) or in a constructor mem-initializer (11.9.3 [class.base.init])...
  12. Change 11.4 [class.mem] paragraph 2 as indicated:

  13. ...Within the class member-specification, the class is regarded as complete within function bodies, default arguments, and exception-specifications, and constructor ctor-initializers (including such things in nested classes)...
  14. Change 11.4 [class.mem] paragraph 9 as indicated:

  15. Each occurrence in an expression of the name of a non-static data member or non-static member function of a class shall be expressed as a class member access (7.6.1.5 [expr.ref]), except when it appears in the formation of a pointer to member (7.6.2.2 [expr.unary.op]), or or when it appears in the body of a non-static member function of its class or of a class derived from its class (11.4.3 [class.mfct.non.static]), or when it appears in a mem-initializer for a constructor for its class or for a class derived from its class (11.9.3 [class.base.init]).
  16. Change the note in 11.4.2 [class.mfct] paragraph 5 as indicated:

  17. [Note: a name used in a member function definition (that is, in the parameter-declaration-clause including the default arguments (9.3.4.7 [dcl.fct.default]), or or in the member function body, or, for a constructor function (11.4.5 [class.ctor]), in a mem-initializer expression (11.9.3 [class.base.init])) is looked up as described in 6.5 [basic.lookup]. —end note]
  18. Change 11.4.3 [class.mfct.non.static] paragraph 1 as indicated:

  19. ...A non-static member function may also be called directly using the function call syntax (7.6.1.3 [expr.call], 12.2.2.2 [over.match.call]) from within the body of a member function of its class or of a class derived from its class.

  20. Change 11.4.3 [class.mfct.non.static] paragraph 3 as indicated:

  21. When an id-expression (_N4567_.5.1.1 [expr.prim.general]) that is not part of a class member access syntax (7.6.1.5 [expr.ref]) and not used to form a pointer to member (7.6.2.2 [expr.unary.op]) is used in the body of a non-static member function of class X or used in the mem-initializer for a constructor of class X, if name lookup (6.5.3 [basic.lookup.unqual]) resolves the name in the id-expression to a non-static non-type member of class X or of a base class of X, the id-expression is transformed into a class member access expression (7.6.1.5 [expr.ref]) using (*this) (_N4868_.11.4.3.2 [class.this]) as the postfix-expression to the left of the . operator...
  22. Change 11.4.5 [class.ctor] paragraph 7 as indicated:

  23. ...The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list no ctor-initializer (11.9.3 [class.base.init]) and an empty function body compound-statement...
  24. Change 11.9.3 [class.base.init] paragraph 4 as indicated:

  25. ...After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor's mem-initializers, nor default-initialized, nor value-initialized, nor given a value during execution of the compound-statement of the body of the constructor, the member has indeterminate value.
  26. Change the last bullet of 11.9.3 [class.base.init] paragraph 5 as indicated:

  27. Change Clause 14 [except] paragraph 4 as indicated:

  28. A function-try-block associates a handler-seq with the ctor-initializer, if present, and the function-body compound-statement. An exception thrown during the execution of the initializer expressions in the ctor-initializer or during the execution of the function-body compound-statement transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers. [Example:

        int f(int);
        class C {
            int i;
            double d;
        public:
            C(int, double);
        };
    
        C::C(int ii, double id)
        try
            : i(f(ii)), d(id)
        {
            // constructor function body statements
        }
        catch (...)
        {
            // handles exceptions thrown from the ctor-initializer
            // and from the constructor function body statements
        }
    

    end example]

  29. Change 14.3 [except.ctor] paragraph 2 as indicated:

  30. When an exception is thrown, control is transferred to the nearest handler with a matching type (14.4 [except.handle]); “nearest” means the handler for which the compound-statement, compound-statement or ctor-initializer, or function-body following the try keyword was most recently entered by the thread of control and not yet exited.



387. Errors in example in 14.6.5

Section: _N4868_.13.8.6  [temp.inject]     Status: CD1     Submitter: Aleksey Gurtovoy     Date: 27 Oct 2002

[Voted into WP at March 2004 meeting.]

The example in _N4868_.13.8.6 [temp.inject] paragraph 2 is incorrect:

  template<typename T> class number {
      number(int);
      //...
      friend number gcd(number& x, number& y) { /* ... */ }
      //...
  };

  void g()
  {
      number<double> a(3), b(4);
      //...
      a = gcd(a,b);   // finds gcd because number<double> is an
                      // associated class, making gcd visible
                      // in its namespace (global scope)
      b = gcd(3,4);   // ill-formed; gcd is not visible
  }

Regardless of the last statement ("b = gcd(3,4);"), the above code is ill-formed:

a) number's constructor is private;

b) the definition of (non-void) friend 'gcd' function does not contain a return statement.

Proposed resolution (April 2003):

Replace the example in _N4868_.13.8.6 [temp.inject] paragraph 2

  template<typename T> class number {
          number(int);
          //...
          friend number gcd(number& x, number& y) { /* ... */ }
          //...
  };

  void g()
  {
          number<double> a(3), b(4);
          //...
          a = gcd(a,b);           //  finds  gcd  because  number<double>  is an
                                  //  associated class, making  gcd  visible
                                  //  in its namespace (global scope)
          b = gcd(3,4);           //  ill-formed;  gcd  is not visible
  }
by
  template<typename T> class number {
     public:
          number(int);
          //...
          friend number gcd(number x, number y) { return 0; }
     private:
          //...
  };

  void g()
  {
          number<double> a(3), b(4);
          //...
          a = gcd(a,b);           //  finds  gcd  because  number<double>  is an
                                  //  associated class, making  gcd  visible
                                  //  in its namespace (global scope)
          b = gcd(3,4);           //  ill-formed;  gcd  is not visible
  }

Drafting note: Added "return" to the friend function, removed references in gcd arguments, added access specifiers.




357. Definition of signature should include name

Section: Clause 3  [intro.defs]     Status: CD1     Submitter: Steve Clamage     Date: 26 May 2002

[Voted into WP at April, 2007 meeting.]

Section Clause 3 [intro.defs], definition of "signature" omits the function name as part of the signature. Since the name participates in overload resolution, shouldn't it be included in the definition? I didn't find a definition of signature in the ARM, but I might have missed it.

Fergus Henderson: I think so. In particular, _N4140_.17.6.4.3.2 [global.names] reserves certain "function signatures" for use by the implementation, which would be wrong unless the signature includes the name.

-2- Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage.

-5- Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.

Other uses of the term "function signature" in the description of the standard library also seem to assume that it includes the name.

James Widman:

Names don't participate in overload resolution; name lookup is separate from overload resolution. However, the word “signature” is not used in Clause 12 [over]. It is used in linkage and declaration matching (e.g., 13.7.7.2 [temp.over.link]). This suggests that the name and scope of the function should be part of its signature.

Proposed resolution (October, 2006):

  1. Replace Clause 3 [intro.defs] “signature” with the following:

  2. the name and the parameter-type-list (9.3.4.6 [dcl.fct]) of a function, as well as the class or namespace of which it is a member. If a function or function template is a class member its signature additionally includes the cv-qualifiers (if any) on the function or function template itself. The signature of a function template additionally includes its return type and its template parameter list. The signature of a function template specialization includes the signature of the template of which it is a specialization and its template arguments (whether explicitly specified or deduced). [Note: Signatures are used as a basis for name-mangling and linking. —end note]
  3. Delete paragraph 3 and replace the first sentence of 13.7.7.2 [temp.over.link] as follows:

  4. The signature of a function template specialization consists of the signature of the function template and of the actual template arguments (whether explicitly specified or deduced).

    The signature of a function template consists of its function signature, its return type and its template parameter list is defined in Clause 3 [intro.defs]. The names of the template parameters are significant...

(See also issue 537.)




537. Definition of “signature”

Section: Clause 3  [intro.defs]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 12 October 2005

[Voted into WP at April, 2007 meeting.]

The standard defines “signature” in two places: Clause 3 [intro.defs] and 13.7.7.2 [temp.over.link] paragraphs 3-4. The former seems to be meant as a formal definition (I think it's the only place covering the nontemplate case), yet it lacks some bits mentioned in the latter (specifically, the notion of a “signature of a function template,” which is part of every signature of the associated function template specializations).

Also, I think the Clause 3 [intro.defs] words “the information about a function that participates in overload resolution” isn't quite right either. Perhaps, “the information about a function that distinguishes it in a set of overloaded functions?”

Eric Gufford:

In Clause 3 [intro.defs] the definition states that “Function signatures do not include return type, because that does not participate in overload resolution,” while 13.7.7.2 [temp.over.link] paragraph 4 states “The signature of a function template consists of its function signature, its return type and its template parameter list.” This seems inconsistent and potentially confusing. It also seems to imply that two identical function templates with different return types are distinct signatures, which is in direct violation of 12.2 [over.match]. 13.7.7.2 [temp.over.link] paragraph 4 should be amended to include verbiage relating to overload resolution.

Either return types are included in function signatures, or they're not, across the board. IMHO, they should be included as they are an integral part of the function declaration/definition irrespective of overloads. Then verbiage should be added about overload resolution to distinguish between signatures and overload rules. This would help clarify things, as it is commonly understood that overload resolution is based on function signature.

In short, the term “function signature” should be made consistent, and removed from its (implicit, explicit or otherwise) linkage to overload resolution as it is commonly understood.

James Widman:

The problem is that (a) if you say the return type is part of the signature of a non-template function, then you have overloading but not overload resolution on return types (i.e., what we have now with function templates). I don't think anyone wants to make the language uglier in that way. And (b) if you say that the return type is not part of the signature of a function template, you will break code. Given those alternatives, it's probably best to maintain the status quo (which the implementors appear to have rendered faithfully).

Proposed resolution (September, 2006):

This issue is resolved by the resolution of issue 357.




362. Order of initialization in instantiation units

Section: 5.2  [lex.phases]     Status: CD1     Submitter: Mark Mitchell     Date: 2 July 2002

[Voted into WP at March 2004 meeting.]

Should this program do what its author obviously expects? As far as I can tell, the standard says that the point of instantiation for Fib<n-1>::Value is the same as the point of instantiation as the enclosing specialization, i.e., Fib<n>::Value. What in the standard actually says that these things get initialized in the right order?

  template<int n>
  struct Fib { static int Value; };

  template <>
  int Fib<0>::Value = 0;

  template <>
  int Fib<1>::Value = 1;

  template<int n>
  int Fib<n>::Value = Fib<n-1>::Value + Fib<n-2>::Value;

  int f ()
  {
    return Fib<40>::Value;
  }

John Spicer: My opinion is that the standard does not specify the behavior of this program. I thought there was a core issue related to this, but I could not find it. The issue that I recall proposed tightening up the static initialization rules to make more cases well defined.

Your comment about point of instantiation is correct, but I don't think that really matters. What matters is the order of execution of the initialization code at execution time. Instantiations don't really live in "translation units" according to the standard. They live in "instantiation units", and the handling of instantiation units in initialization is unspecified (which should probably be another core issue). See 5.2 [lex.phases] paragraph 8.

Notes from October 2002 meeting:

We discussed this and agreed that we really do mean the the order is unspecified. John Spicer will propose wording on handling of instantiation units in initialization.

Proposed resolution (April 2003):

TC1 contains the following text in 6.9.3.2 [basic.start.static] paragraph 1:

Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.

This was revised by issue 270 to read:

Dynamic initialization of an object is either ordered or unordered. Explicit specializations and definitions of class template static data members have ordered initialization. Other class template static data member instances have unordered initialization. Other objects defined in namespace scope have ordered initialization. Objects defined within a single translation unit and with ordered initialization shall be initialized in the order of their definitions in the translation unit. The order of initialization is unspecified for objects with unordered initialization and for objects defined in different translation units.

This addresses this issue but while reviewing this issue some additional changes were suggested for the above wording:

Dynamic initialization of an object is either ordered or unordered. Definitions of explicitly specialized Explicit specializations and definitions of class template static data members have ordered initialization. Other class template static data members (i.e., implicitly or explicitly instantiated specializations) instances have unordered initialization. Other objects defined in namespace scope have ordered initialization. Objects defined within a single translation unit and with ordered initialization shall be initialized in the order of their definitions in the translation unit. The order of initialization is unspecified for objects with unordered initialization and for objects defined in different translation units.



558. Excluded characters in universal character names

Section: 5.3  [lex.charset]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 8 February 2006

[Moved to DR at October 2007 meeting.]

C99 and C++ differ in their approach to universal character names (UCNs).

Issue 248 already covers the differences in UCNs allowed for identifiers, but a more fundamental issue is that of UCNs that correspond to codes reserved by ISO 10676 for surrogate pair forms.

Specifically, C99 does not allow UCNs whose short names are in the range 0xD800 to 0xDFFF. I think C++ should have the same constraint. If someone really wants to place such a code in a character or string literal, they should use a hexadecimal escape sequence instead, for example:

    wchar_t  w1 = L'\xD900'; // Okay.
    wchar_t  w2 = L'\uD900'; // Error, not a valid character.

(Compare 6.4.3 paragraph 2 in ISO/IEC 9899/1999 with 5.3 [lex.charset] paragraph 2 in the C++ standard.)

Proposed resolution (October, 2007):

This issue is resolved by the adoption of paper J16/07-0030 = WG21 N2170.




505. Conditionally-supported behavior for unknown character escapes

Section: 5.13.3  [lex.ccon]     Status: CD1     Submitter: Mike Miller     Date: 14 Apr 2005

[Voted into WP at the October, 2006 meeting.]

The current wording of 5.13.3 [lex.ccon] paragraph 3 states,

If the character following a backslash is not one of those specified, the behavior is undefined.

Paper J16/04-0167=WG21 N1727 suggests that such character escapes be ill-formed. In discussions at the Lillehammer meeting, however, the CWG felt that the newly-approved category of conditionally-supported behavior would be more appropriate.

Proposed resolution (April, 2006):

Change the next-to-last sentence of 5.13.3 [lex.ccon] paragraph 3 from:

If the character following a backslash is not one of those specified, the behavior is undefined.

to:

Escape sequences in which the character following the backslash is not listed in Table 6 are conditionally-supported, with implementation-defined semantics.



309. Linkage of entities whose names are not simply identifiers, in introduction

Section: 6.1  [basic.pre]     Status: CD1     Submitter: Mike Miller     Date: 17 Sep 2001

[Voted into the WP at the June, 2008 meeting.]

6.1 [basic.pre] paragraph 10, while not incorrect, does not allow for linkage of operators and conversion functions. It says:

An identifier used in more than one translation unit can potentially refer to the same entity in these translation units depending on the linkage (6.6 [basic.link]) of the identifier specified in each translation unit.

Proposed Resolution (November, 2006):

This issue is resolved by the proposed resolution of issue 485.




485. What is a “name”?

Section: 6.1  [basic.pre]     Status: CD1     Submitter: Gabriel Dos Reis     Date: 9 Nov 2004

[Voted into the WP at the June, 2008 meeting.]

6.1 [basic.pre] paragraph 4 says:

A name is a use of an identifier (5.10 [lex.name]) that denotes an entity or label (8.7.6 [stmt.goto], 8.2 [stmt.label]).

Just three paragraphs later, it says

Two names are the same if

The last two bullets contradict the definition of name in paragraph 4 because they are not identifiers.

This definition affects other parts of the Standard, as well. For example, in 6.5.4 [basic.lookup.argdep] paragraph 1,

When an unqualified name is used as the postfix-expression in a function call (7.6.1.3 [expr.call]), other namespaces not considered during the usual unqualified lookup (6.5.3 [basic.lookup.unqual]) may be searched, and in those namespaces, namespace-scope friend function declarations (11.8.4 [class.friend]) not otherwise visible may be found.

With the current definition of name, argument-dependent lookup apparently does not apply to function-notation calls to overloaded operators.

Another related question is whether a template-id is a name or not and thus would trigger an argument-dependent lookup. Personally, I have always viewed a template-id as a name, just like operator+.

Proposed Resolution (November, 2006):

  1. Change 6.1 [basic.pre] paragraphs 3-8 as follows:

    1. An entity is a value, object, subobject, base class subobject, array element, variable, reference, function, instance of a function, enumerator, type, class member, template, template specialization, namespace, or parameter pack.

    2. A name is a use of an identifier identifier (5.10 [lex.name]), operator-function-id (12.4 [over.oper]), conversion-function-id (11.4.8.3 [class.conv.fct]), or template-id (13.3 [temp.names]) that denotes an entity or label (8.7.6 [stmt.goto], 8.2 [stmt.label]). A variable is introduced by the declaration of an object. The variable's name denotes the object.

    3. Every name that denotes an entity is introduced by a declaration. Every name that denotes a label is introduced either by a goto statement (8.7.6 [stmt.goto]) or a labeled-statement (8.2 [stmt.label]).

    4. A variable is introduced by the declaration of an object. The variable's name denotes the object.

    5. Some names denote types, classes, enumerations, or templates. In general, it is necessary to determine whether or not a name denotes one of these entities before parsing the program that contains it. The process that determines this is called name lookup (6.5 [basic.lookup]).

    6. Two names are the same if

      • they are identifiers identifiers composed of the same character sequence; or

      • they are the names of overloaded operator functions operator-function-ids formed with the same operator; or

      • they are the names of user-defined conversion functions conversion-function-ids formed with the same type., or

      • they are template-ids that refer to the same class or function (13.6 [temp.type]).

    7. An identifier A name used in more than one translation unit can potentially refer to the same entity in these translation units depending on the linkage (6.6 [basic.link]) of the identifier name specified in each translation unit.

  2. Change 6.4.6 [basic.scope.class] paragraph 1 item 5 as follows:

    The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, member function definitions (including the member function body and any portion of the declarator part of such definitions which follows the identifier declarator-id, including a parameter-declaration-clause and any default arguments (9.3.4.7 [dcl.fct.default]).

    [Drafting note: This last change is not really mandated by the issue, but it's another case of “identifier” confusion.]

(This proposed resolution also resolves issue 309.)




261. When is a deallocation function "used?"

Section: 6.3  [basic.def.odr]     Status: CD1     Submitter: Mike Miller     Date: 7 Nov 2000

[Moved to DR at October 2002 meeting.]

6.3 [basic.def.odr] paragraph 2 says that a deallocation function is "used" by a new-expression or delete-expression appearing in a potentially-evaluated expression. 6.3 [basic.def.odr] paragraph 3 requires only that "used" functions be defined.

This wording runs afoul of the typical implementation technique for polymorphic delete-expressions in which the deallocation function is invoked from the virtual destructor of the most-derived class. The problem is that the destructor must be defined, because it's virtual, and if it contains an implicit reference to the deallocation function, the deallocation function must also be defined, even if there are no relevant new-expressions or delete-expressions in the program.

For example:

        struct B { virtual ~B() { } };

        struct D: B {
            void operator delete(void*);
            ~D() { }
        };

Is it required that D::operator delete(void*) be defined, even if no B or D objects are ever created or deleted?

Suggested resolution: Add the words "or if it is found by the lookup at the point of definition of a virtual destructor (11.4.7 [class.dtor])" to the specification in 6.3 [basic.def.odr] paragraph 2.

Notes from 04/01 meeting:

The consensus was in favor of requiring that any declared non-placement operator delete member function be defined if the destructor for the class is defined (whether virtual or not), and similarly for a non-placement operator new if a constructor is defined.

Proposed resolution (10/01):

In 6.3 [basic.def.odr] paragraph 2, add the indicated text:

An allocation or deallocation function for a class is used by a new expression appearing in a potentially-evaluated expression as specified in 7.6.2.8 [expr.new] and 11.4.11 [class.free]. A deallocation function for a class is used by a delete expression appearing in a potentially-evaluated expression as specified in 7.6.2.9 [expr.delete] and 11.4.11 [class.free]. A non-placement allocation or deallocation function for a class is used by the definition of a constructor of that class. A non-placement deallocation function for a class is 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 (11.4.7 [class.dtor]). [Footnote: An implementation is not required to call allocation and deallocation functions from constructors or destructors; however, this is a permissible implementation technique.]




289. Incomplete list of contexts requiring a complete type

Section: 6.3  [basic.def.odr]     Status: CD1     Submitter: Mike Miller     Date: 25 May 2001

[Moved to DR at October 2002 meeting.]

6.3 [basic.def.odr] paragraph 4 has a note listing the contexts that require a class type to be complete. It does not list use as a base class as being one of those contexts.

Proposed resolution (10/01):

In 6.3 [basic.def.odr] paragraph 4 add a new bullet at the end of the note as the next-to-last bullet:




433. Do elaborated type specifiers in templates inject into enclosing namespace scope?

Section: 6.4.2  [basic.scope.pdecl]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 2 September 2003

[Voted into WP at March 2004 meeting.]

Consider the following translation unit:

  template<class T> struct S {
    void f(union U*);  // (1)
  };
  template<class T> void S<T>::f(union U*) {}  // (2)
  U *p;  // (3)

Does (1) introduce U as a visible name in the surrounding namespace scope?

If not, then (2) could presumably be an error since the "union U" in that definition does not find the same type as the declaration (1).

If yes, then (3) is OK too. However, we have gone through much trouble to allow template implementations that do not pre-parse the template definitions, but requiring (1) to be visible would change that.

A slightly different case is the following:

  template<typename> void f() { union U *p; }
  U *q;  // Should this be valid?

Notes from October 2003 meeting:

There was consensus that example 1 should be allowed. (Compilers already parse declarations in templates; even MSVC++ 6.0 accepts this case.) The vote was 7-2.

Example 2, on the other hand, is wrong; the union name goes into a block scope anyway.

Proposed resolution:

In 6.4.2 [basic.scope.pdecl] change the second bullet of paragraph 5 as follows:

for an elaborated-type-specifier of the form
   class-key identifier
if the elaborated-type-specifier is used in the decl-specifier-seq or parameter-declaration-clause of a function defined in namespace scope, the identifier is declared as a class-name in the namespace that contains the declaration; otherwise, except as a friend declaration, the identifier is declared in the smallest non-class, non-function-prototype scope that contains the declaration. [Note: These rules also apply within templates.] [Note: ...]



432. Is injected class name visible in base class specifier list?

Section: 6.4.6  [basic.scope.class]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 29 August 2003

[Voted into WP at March 2004 meeting.]

Consider the following example (inspired by a question from comp.lang.c++.moderated):

  template<typename> struct B {};
  template<typename T> struct D: B<D> {};

Most (all?) compilers reject this code because D is handled as a template name rather than as the injected class name.

Clause 11 [class]/2 says that the injected class name is "inserted into the scope of the class."

6.4.6 [basic.scope.class]/1 seems to be the text intended to describe what "scope of a class" means, but it assumes that every name in that scope was introduced using a "declarator". For an implicit declaration such as the injected-class name it is not clear what that means.

So my questions:

  1. Should the injected class name be available in the base class specifiers?
    John Spicer: I do not believe the injected class name should be available in the base specifier. I think the semantics of injected class names should be as if a magic declaration were inserted after the opening "{" of the class definition. The injected class name is a member of the class and members don't exist at the point where the base specifiers are scanned.
  2. Do you agree the wording should be clarified whatever the answer to the first question?
    John Spicer: I believe the 6.4.6 [basic.scope.class] wording should be updated to reflect the fact that not all names come from declarators.

Notes from October 2003 meeting:

We agree with John Spicer's suggested answers above.

Proposed Resolution (October 2003):

The answer to question 1 above is No and no change is required.

For question 1, change 6.4.6 [basic.scope.class] paragraph 1 rule 1 to:

1) The potential scope of a name declared in a class consists not only of the declarative region following the name's point of declaration declarator, but also of all function bodies, default arguments, and constructor ctor-initializers in that class (including such things in nested classes). The point of declaration of an injected-class-name (Clause 11 [class]) is immediately following the opening brace of the class definition.

(Note that this change overlaps a change in issue 417.)

Also change 6.4.2 [basic.scope.pdecl] by adding a new paragraph 8 for the injected-class-name case:

The point of declaration for an injected-class-name (Clause 11 [class]) is immediately following the opening brace of the class definition.

Alternatively this paragraph could be added after paragraph 5 and before the two note paragraphs (i.e. it would become paragraph 5a).




39. Conflicting ambiguity rules

Section: 6.5.2  [class.member.lookup]     Status: CD1     Submitter: Neal M Gafter     Date: 20 Aug 1998

[Voted into WP at April 2005 meeting.]

The ambiguity text in 6.5.2 [class.member.lookup] may not say what we intended. It makes the following example ill-formed:

    struct A {
        int x(int);
    };
    struct B: A {
        using A::x;
        float x(float);
    };

    int f(B* b) {
        b->x(3);  // ambiguous
    }
This is a name lookup ambiguity because of 6.5.2 [class.member.lookup] paragraph 2:
... Each of these declarations that was introduced by a using-declaration is considered to be from each sub-object of C that is of the type containing the declaration designated by the using-declaration. If the resulting set of declarations are not all from sub-objects of the same type, or the set has a nonstatic member and includes members from distinct sub-objects, there is an ambiguity and the program is ill-formed.
This contradicts the text and example in paragraph 12 of 9.9 [namespace.udecl] .

Proposed Resolution (10/00):

  1. Replace the two cited sentences from 6.5.2 [class.member.lookup] paragraph 2 with the following:

    The resulting set of declarations shall all be from sub-objects of the same type, or there shall be a set of declarations from sub-objects of a single type that contains using-declarations for the declarations found in all other sub-object types. Furthermore, for nonstatic members, the resulting set of declarations shall all be from a single sub-object, or there shall be a set of declarations from a single sub-object that contains using-declarations for the declarations found in all other sub-objects. Otherwise, there is an ambiguity and the program is ill-formed.
  2. Replace the examples in 6.5.2 [class.member.lookup] paragraph 3 with the following:

        struct A {
            int x(int);
            static int y(int);
        };
        struct V {
            int z(int);
        };
        struct B: A, virtual V {
            using A::x;
            float x(float);
            using A::y;
            static float y(float);
            using V::z;
            float z(float);
        };
        struct C: B, A, virtual V {
        };
    
        void f(C* c) {
            c->x(3);    // ambiguous -- more than one sub-object A
            c->y(3);    // not ambiguous
            c->z(3);    // not ambiguous
        }
    

Notes from 04/01 meeting:

The following example should be accepted but is rejected by the wording above:

    struct A { static void f(); };

    struct B1: virtual A {
        using A::f;
    };

    struct B2: virtual A {
        using A::f;
    };

    struct C: B1, B2 { };

    void g() {
        C::f();        // OK, calls A::f()
    }

Notes from 10/01 meeting (Jason Merrill):

The example in the issues list:

    struct A {
        int x(int);
    };
    struct B: A {
        using A::x;
        float x(float);
    };

    int f(B* b) {
        b->x(3);  // ambiguous
    }
Is broken under the existing wording:
... Each of these declarations that was introduced by a using-declaration is considered to be from each sub-object of C that is of the type containing the declaration designated by the using-declaration. If the resulting set of declarations are not all from sub-objects of the same type, or the set has a nonstatic member and includes members from distinct sub-objects, there is an ambiguity and the program is ill-formed.
Since the two x's are considered to be "from" different objects, looking up x produces a set including declarations "from" different objects, and the program is ill-formed. Clearly this is wrong. The problem with the existing wording is that it fails to consider lookup context.

The first proposed solution:

The resulting set of declarations shall all be from sub-objects of the same type, or there shall be a set of declarations from sub-objects of a single type that contains using-declarations for the declarations found in all other sub-object types. Furthermore, for nonstatic members, the resulting set of declarations shall all be from a single sub-object, or there shall be a set of declarations from a single sub-object that contains using-declarations for the declarations found in all other sub-objects. Otherwise, there is an ambiguity and the program is ill-formed.
breaks this testcase:
    struct A { static void f(); };

    struct B1: virtual A {
        using A::f;
    };

    struct B2: virtual A {
        using A::f;
    };

    struct C: B1, B2 { };

    void g() {
        C::f();        // OK, calls A::f()
    }
because it considers the lookup context, but not the definition context; under this definition of "from", the two declarations found are the using-declarations, which are "from" B1 and B2.

The solution is to separate the notions of lookup and definition context. I have taken an algorithmic approach to describing the strategy.

Incidentally, the earlier proposal allows one base to have a superset of the declarations in another base; that was an extension, and my proposal does not do that. One algorithmic benefit of this limitation is to simplify the case of a virtual base being hidden along one arm and not another ("domination"); if we allowed supersets, we would need to remember which subobjects had which declarations, while under the following resolution we need only keep two lists, of subobjects and declarations.

Proposed resolution (October 2002):

Replace 6.5.2 [class.member.lookup] paragraph 2 with:

The following steps define the result of name lookup for a member name f in a class scope C.

The lookup set for f in C, called S(f,C), consists of two component sets: the declaration set, a set of members named f; and the subobject set, a set of subobjects where declarations of these members (possibly including using-declarations) were found. In the declaration set, using-declarations are replaced by the members they designate, and type declarations (including injected-class-names) are replaced by the types they designate. S(f,C) is calculated as follows.

If C contains a declaration of the name f, the declaration set contains every declaration of f in C (excluding bases), the subobject set contains C itself, and calculation is complete.

Otherwise, S(f,C) is initially empty. If C has base classes, calculate the lookup set for f in each direct base class subjobject Bi, and merge each such lookup set S(f,Bi) in turn into S(f,C).

The following steps define the result of merging lookup set S(f,Bi) into the intermediate S(f,C):

The result of name lookup for f in C is the declaration set of S(f,C). If it is an invalid set, the program is ill-formed.

[Example:

    struct A { int x; };                    // S(x,A) = {{ A::x }, { A }}
    struct B { float x; };                  // S(x,B) = {{ B::x }, { B }}
    struct C: public A, public B { };       // S(x,C) = { invalid, { A in C, B in C }}
    struct D: public virtual C { };         // S(x,D) = S(x,C)
    struct E: public virtual C { char x; }; // S(x,E) = {{ E::x }, { E }}
    struct F: public D, public E { };       // S(x,F) = S(x,E)

    int main() {
      F f;
      f.x = 0;   // OK, lookup finds { E::x }
    }
S(x,F) is unambiguous because the A and B base subobjects of D are also base subobjects of E, so S(x,D) is discarded in the first merge step. --end example]

Turn 6.5.2 [class.member.lookup] paragraphs 5 and 6 into notes.

Notes from October 2003 meeting:

Mike Miller raised some new issues in N1543, and we adjusted the proposed resolution as indicated in that paper.

Further information from Mike Miller (January 2004):

Unfortunately, I've become aware of a minor glitch in the proposed resolution for issue 39 in N1543, so I'd like to suggest a change that we can discuss in Sydney.

A brief review and background of the problem: the major change we agreed on in Kona was to remove detection of multiple-subobject ambiguity from class lookup (6.5.2 [class.member.lookup]) and instead handle it as part of the class member access expression. It was pointed out in Kona that 11.8.3 [class.access.base]/5 has this effect:

If a class member access operator, including an implicit "this->," is used to access a nonstatic data member or nonstatic member function, the reference is ill-formed if the left operand (considered as a pointer in the "." operator case) cannot be implicitly converted to a pointer to the naming class of the right operand.

After the meeting, however, I realized that this requirement is not sufficient to handle all the cases. Consider, for instance,

    struct B {
        int i;
    };

    struct I1: B { };
    struct I2: B { };

    struct D: I1, I2 {
        void f() {
            i = 0;    // not ill-formed per 11.2p5
        }
    };

Here, both the object expression ("this") and the naming class are "D", so the reference to "i" satisfies the requirement in 11.8.3 [class.access.base]/5, even though it involves a multiple-subobject ambiguity.

In order to address this problem, I proposed in N1543 to add a paragraph following 7.6.1.5 [expr.ref]/4:

If E2 is a non-static data member or a non-static member function, the program is ill-formed if the class of E1 cannot be unambiguously converted (10.2) to the class of which E2 is directly a member.

That's not quite right. It does diagnose the case above as written; however, it breaks the case where qualification is used to circumvent the ambiguity:

    struct D2: I1, I2 {
        void f() {
            I2::i = 0;    // ill-formed per proposal
        }
    };

In my proposed wording, the class of "this" can't be converted to "B" (the qualifier is ignored), so the access is ill-formed. Oops.

I think the following is a correct formulation, so the proposed resolution we discuss in Sydney should contain the following paragraph instead of the one in N1543:

If E2 is a nonstatic data member or a non-static member function, the program is ill-formed if the naming class (11.2) of E2 cannot be unambiguously converted (10.2) to the class of which E2 is directly a member.

This reformulation also has the advantage of pointing readers to 11.8.3 [class.access.base], where the the convertibility requirement from the class of E1 to the naming class is located and which might otherwise be overlooked.

Notes from the March 2004 meeting:

We discussed this further and agreed with these latest recommendations. Mike Miller has produced a paper N1626 that gives just the final collected set of changes.

(This resolution also resolves isssue 306.)




306. Ambiguity by class name injection

Section: 6.5.2  [class.member.lookup]     Status: CD1     Submitter: Clark Nelson     Date: 19 Jul 2001

[Voted into WP at April 2005 meeting.]

Is the following well-formed?

    struct A {
        struct B { };
    };
    struct C : public A, public A::B {
        B *p;
    };
The lookup of B finds both the struct B in A and the injected B from the A::B base class. Are they the same thing? Does the standard say so?

What if a struct is found along one path and a typedef to that struct is found along another path? That should probably be valid, but does the standard say so?

This is resolved by issue 39

February 2004: Moved back to "Review" status because issue 39 was moved back to "Review".




139. Error in friend lookup example

Section: 6.5.3  [basic.lookup.unqual]     Status: CD1     Submitter: Mike Miller     Date: 14 Jul 1999

[Moved to DR at 10/01 meeting.]

The example in 6.5.3 [basic.lookup.unqual] paragraph 3 is incorrect:

    typedef int f;
    struct A {
        friend void f(A &);
        operator int();
        void g(A a) {
            f(a);
        }
    };
Regardless of the resolution of other issues concerning the lookup of names in friend declarations, this example is ill-formed (the function and the typedef cannot exist in the same scope).

One possible repair of the example would be to make f a class with a constructor taking either A or int as its parameter.

(See also issues 95, 136, 138, 143, 165, and 166.)

Proposed resolution (04/01):

  1. Change the example in 6.5.3 [basic.lookup.unqual] paragraph 3 to read:

        typedef int f;
        namespace N {
            struct A {
                friend int f(A &);
                operator int();
                void g(A a) {
                    int i = f(a);
                          // f is the typedef, not the friend function:
                          // equivalent to int(a)
                }
            };
        }
    
  2. Delete the sentence immediately following the example:

    The expression f(a) is a cast-expression equivalent to int(a).



514. Is the initializer for a namespace member in the scope of the namespace?

Section: 6.5.3  [basic.lookup.unqual]     Status: CD1     Submitter: Mike Miller     Date: 24 Mar 2005

[Voted into WP at the October, 2006 meeting.]

Is the following code well-formed?

    namespace N {
      int i;
      extern int j;
    }
    int N::j = i;

The question here is whether the lookup for i in the initializer of N::j finds the declaration in namespace N or not. Implementations differ on this question.

If N::j were a static data member of a class, the answer would be clear: both 6.5.3 [basic.lookup.unqual] paragraph 12 and 9.4 [dcl.init] paragraph 11 say that the initializer “is in the scope of the member's class.” There is no such provision for namespace members defined outside the namespace, however.

The reasoning given in 6.5.3 [basic.lookup.unqual] may be instructive:

A name used in the definition of a static data member of class X (11.4.9.3 [class.static.data]) (after the qualified-id of the static member) is looked up as if the name was used in a member function of X.

It is certainly the case that a name used in a function that is a member of a namespace is looked up in that namespace (6.5.3 [basic.lookup.unqual] paragraph 6), regardless of whether the definition is inside or outside that namespace. Initializers for namespace members should probably be looked up the same way.

Proposed resolution (April, 2006):

Add a new paragraph following 6.5.3 [basic.lookup.unqual] paragraph 12:

If a variable member of a namespace is defined outside of the scope of its namespace then any name used in the definition of the variable member (after the declarator-id) is looked up as if the definition of the variable member occurred in its namespace. [Example:

    namespace N {
      int i = 4;
      extern int j;
    }

    int i = 2;

    int N::j = i;	// N::j == 4

end example]




143. Friends and Koenig lookup

Section: 6.5.4  [basic.lookup.argdep]     Status: CD1     Submitter: Mike Miller     Date: 21 Jul 1999

[Moved to DR at 4/02 meeting.]

Paragraphs 1 and 2 of 6.5.4 [basic.lookup.argdep] say, in part,

When an unqualified name is used as the postfix-expression in a function call (7.6.1.3 [expr.call] )... namespace-scope friend function declarations (11.8.4 [class.friend] ) not otherwise visible may be found... the set of declarations found by the lookup of the function name [includes] the set of declarations found in the... classes associated with the argument types.
The most straightforward reading of this wording is that if a function of namespace scope (as opposed to a class member function) is declared as a friend in a class, and that class is an associated class in a function call, the friend function will be part of the overload set, even if it is not visible to normal lookup.

Consider the following example:

    namespace A {
	class S;
    };
    namespace B {
	void f(A::S);
    };
    namespace A {
	class S {
	    int i;
	    friend void B::f(S);
	};
    }
    void g() {
	A::S s;
	f(s); // should find B::f(A::S)
    }
This example would seem to satisfy the criteria from 6.5.4 [basic.lookup.argdep] : A::S is an associated class of the argument, and A::S has a friend declaration of the namespace-scope function B::f(A::S), so Koenig lookup should include B::f(A::S) as part of the overload set in the call.

Another interpretation is that, instead of finding the friend declarations in associated classes, one only looks for namespace-scope functions, visible or invisible, in the namespaces of which the the associated classes are members; the only use of the friend declarations in the associated classes is to validate whether an invisible function declaration came from an associated class or not and thus whether it should be included in the overload set or not. By this interpretation, the call f(s) in the example will fail, because B::f(A::S) is not a member of namespace A and thus is not found by the lookup.

Notes from 10/99 meeting: The second interpretation is correct. The wording should be revised to make clear that Koenig lookup works by finding "invisible" declarations in namespace scope and not by finding friend declarations in associated classes.

Proposed resolution (04/01): The "associated classes" are handled adequately under this interpretation by 6.5.4 [basic.lookup.argdep] paragraph 3, which describes the lookup in the associated namespaces as including the friend declarations from the associated classes. Other mentions of the associated classes should be removed or qualified to avoid the impression that there is a lookup in those classes:

  1. In 6.5.4 [basic.lookup.argdep], change

    When an unqualified name is used as the postfix-expression in a function call (7.6.1.3 [expr.call]), other namespaces not considered during the usual unqualified lookup (6.5.3 [basic.lookup.unqual]) may be searched, and namespace-scope friend function declarations (11.8.4 [class.friend]) not otherwise visible may be found.

    to

    When an unqualified name is used as the postfix-expression in a function call (7.6.1.3 [expr.call]), other namespaces not considered during the usual unqualified lookup (6.5.3 [basic.lookup.unqual]) may be searched, and in those namespaces, namespace-scope friend function declarations (11.8.4 [class.friend]) not otherwise visible may be found.
  2. In 6.5.4 [basic.lookup.argdep] paragraph 2, delete the words and classes in the following two sentences:

    If the ordinary unqualified lookup of the name finds the declaration of a class member function, the associated namespaces and classes are not considered. Otherwise the set of declarations found by the lookup of the function name is the union of the set of declarations found using ordinary unqualified lookup and the set of declarations found in the namespaces and classes associated with the argument types.

(See also issues 95, 136, 138, 139, 165, 166, and 218.)




218. Specification of Koenig lookup

Section: 6.5.4  [basic.lookup.argdep]     Status: CD1     Submitter: Hyman Rosen     Date: 28 Mar 2000

[Voted into WP at April, 2007 meeting.]

The original intent of the Committee when Koenig lookup was added to the language was apparently something like the following:

  1. The name in the function call expression is looked up like any other unqualified name.
  2. If the ordinary unqualified lookup finds nothing or finds the declaration of a (non-member) function, function template, or overload set, argument-dependent lookup is done and any functions found in associated namespaces are added to the result of the ordinary lookup.

This approach is not reflected in the current wording of the Standard. Instead, the following appears to be the status quo:

  1. Lookup of an unqualified name used as the postfix-expression in the function call syntax always performs Koenig lookup (6.5.3 [basic.lookup.unqual] paragraph 3).
  2. Unless ordinary lookup finds a class member function, the result of Koenig lookup always includes the declarations found in associated namespaces (6.5.4 [basic.lookup.argdep] paragraph 2), regardless of whether ordinary lookup finds a declaration and, if so, what kind of entity is found.
  3. The declarations from associated namespaces are not limited to functions and template functions by anything in 6.5.4 [basic.lookup.argdep]. However, if Koenig lookup results in more than one declaration and at least one of the declarations is a non-function, the program is ill-formed (9.8.4 [namespace.udir], paragraph 4; although this restriction is in the description of the using-directive, the wording applies to any lookup that spans namespaces).

John Spicer: Argument-dependent lookup was created to solve the problem of looking up function names within templates where you don't know which namespace to use because it may depend on the template argument types (and was then expanded to permit use in nontemplates). The original intent only concerned functions. The safest and simplest change is to simply clarify the existing wording to that effect.

Bill Gibbons: I see no reason why non-function declarations should not be found. It would take a special rule to exclude "function objects", as well as pointers to functions, from consideration. There is no such rule in the standard and I see no need for one.

There is also a problem with the wording in 6.5.4 [basic.lookup.argdep] paragraph 2:

If the ordinary unqualified lookup of the name finds the declaration of a class member function, the associated namespaces and classes are not considered.

This implies that if the ordinary lookup of the name finds the declaration of a data member which is a pointer to function or function object, argument-dependent lookup is still done.

My guess is that this is a mistake based on the incorrect assumption that finding any member other than a member function would be an error. I would just change "class member function" to "class member" in the quoted sentence.

Mike Miller: In light of the issue of "short-circuiting" Koenig lookup when normal lookup finds a non-function, perhaps it should be written as "...finds the declaration of a class member, an object, or a reference, the associated namespaces..."?

Andy Koenig: I think I have to weigh in on the side of extending argument-dependent lookup to include function objects and pointers to functions. I am particularly concerned about [function objects], because I think that programmers should be able to replace functions by function objects without changing the behavior of their programs in fundamental ways.

Bjarne Stroustrup: I don't think we could seriously argue from first principles that [argument-dependent lookup should find only function declarations]. In general, C++ name lookup is designed to be independent of type: First we find the name(s), then, we consider its(their) meaning. 6.5 [basic.lookup] states "The name lookup rules apply uniformly to all names ..." That is an important principle.

Thus, I consider text that speaks of "function call" instead of plain "call" or "application of ()" in the context of koenig lookup an accident of history. I find it hard to understand how 7.6.1.3 [expr.call] doesn't either disallow all occurrences of x(y) where x is a class object (that's clearly not intended) or requires koenig lookup for x independently of its type (by reference from 6.5 [basic.lookup]). I suspect that a clarification of 7.6.1.3 [expr.call] to mention function objects is in order. If the left-hand operand of () is a name, it should be looked up using koenig lookup.

John Spicer: This approach causes otherwise well-formed programs to be ill-formed, and it does so by making names visible that might be completely unknown to the author of the program. Using-directives already do this, but argument-dependent lookup is different. You only get names from using-directives if you actually use using-directives. You get names from argument-dependent lookup whether you want them or not.

This basically breaks an important reason for having namespaces. You are not supposed to need any knowledge of the names used by a namespace.

But this example breaks if argument-dependent lookup finds non-functions and if the translation unit includes the <list> header somewhere.

    namespace my_ns {
        struct A {};
        void list(std::ostream&, A&);

        void f() {
            my_ns::A a;
            list(cout, a);
        }
    }

This really makes namespaces of questionable value if you still need to avoid using the same name as an entity in another namespace to avoid problems like this.

Erwin Unruh: Before we really decide on this topic, we should have more analysis on the impact on programs. I would also like to see a paper on the possibility to overload functions with function surrogates (no, I won't write one). Since such an extension is bound to wait until the next official update, we should not preclude any outcome of the discussion.

I would like to have a change right now, which leaves open several outcomes later. I would like to say that:

Koenig lookup will find non-functions as well. If it finds a variable, the program is ill-formed. If the primary lookup finds a variable, Koenig lookup is done. If the result contains both functions and variables, the program is ill-formed. [Note: A future standard will assign semantics to such a program.]

I myself are not comfortable with this as a long-time result, but it prepares the ground for any of the following long term solutions:

The note is there to prevent compiler vendors to put their own extensions in here.

(See also issues 113 and 143.)

Notes from 04/00 meeting:

Although many agreed that there were valid concerns motivating a desire for Koenig lookup to find non-function declarations, there was also concern that supporting this capability would be more dangerous than helpful in the absence of overload resolution for mixed function and non-function declarations.

A straw poll of the group revealed 8 in favor of Koenig lookup finding functions and function templates only, while 3 supported the broader result.

Notes from the 10/01 meeting:

There was unanimous agreement on one less controversial point: if the normal lookup of the identifier finds a non-function, argument-dependent lookup should not be done.

On the larger issue, the primary point of consensus is that making this change is an extension, and therefore it should wait until the point at which we are considering extensions (which could be very soon). There was also consensus on the fact that the standard as it stands is not clear: some introductory text suggests that argument-dependent lookup finds only functions, but the more detailed text that describes the lookup does not have any such restriction.

It was also noted that some existing implementations (e.g., g++) do find some non-functions in some cases.

The issue at this point is whether we should (1) make a small change to make the standard clear (presumably in the direction of not finding the non-functions in the lookup), and revisit the issue later as an extension, or (2) leave the standard alone for now and make any changes only as part of considering the extension. A straw vote favored option (1) by a strong majority.

Additional Notes (September, 2006):

Recent discussion of this issue has emphasized the following points:

  1. The concept of finding function pointers and function objects as part of argument-dependent lookup is not currently under active discussion in the Evolution Working Group.

  2. The major area of concern with argument-dependent lookup is finding functions in unintended namespaces. There are current proposals to deal with this concern either by changing the definition of “associated namespace” so that fewer namespaces are considered or to provide a mechanism for enabling or disabling ADL altogether. Although this concern is conceptually distinct from the question of whether ADL finds function pointers and function objects, it is related in the sense that the current rules are perceived as finding too many functions (because of searching too many namespaces), and allowing function pointers and function objects would also increase the number of entities found by ADL.

  3. Any expansion of ADL to include function pointers and function objects must necessarily update the overloading rules to specify how they interact with functions and function templates in the overload set. Current implementation experience (g++) is not helpful in making this decision because, although it performs a uniform lookup and finds non-function entities, it diagnoses an error in overload resolution if non-function entities are in the overload set.

  4. There is a possible problem if types are found by ADL: it is not clear that overloading between callable entities (functions, function templates, function pointers, and function objects) and types (where the postfix syntax means a cast or construction of a temporary) is reasonable or useful.

James Widman:

There is a larger debate here about whether ADL should find object names; the proposed wording below is only intended to answer the request for wording to clarify the status quo (option 1 above) and not to suggest the outcome of the larger debate.

Proposed Resolution (October, 2006):

  1. Replace the normative text in 6.5.4 [basic.lookup.argdep] paragraph 3 with the following (leaving the text of the note and example unchanged):

    Let X be the lookup set produced by unqualified lookup (6.5.3 [basic.lookup.unqual]) and let Y be the lookup set produced by argument dependent lookup (defined as follows). If X contains

    • a declaration of a class member, or
    • a block-scope function declaration that is not a using-declaration, or
    • a declaration that is neither a function nor a function template

    then Y is empty. Otherwise Y is the set of declarations found in the namespaces associated with the argument types as described below. The set of declarations found by the lookup of the name is the union of X and Y.

  2. Change 6.5.3 [basic.lookup.unqual] paragraph 4 as indicated:

    When considering an associated namespace, the lookup is the same as the lookup performed when the associated namespace is used as a qualifier (6.5.5.3 [namespace.qual]) except that:

    • Any using-directives in the associated namespace are ignored.
    • Any namespace-scope friend functions or friend function templates declared in associated classes are visible within their respective namespaces even if they are not visible during an ordinary lookup (11.8.4 [class.friend]).
    • All names except those of (possibly overloaded) functions and function templates are ignored.




403. Reference to a type as a template-id

Section: 6.5.4  [basic.lookup.argdep]     Status: CD1     Submitter: John Spicer     Date: 18 Sep 2003

[Voted into WP at March 2004 meeting.]

Spun off from issue 384.

6.5.4 [basic.lookup.argdep] says:

If T is a template-id, its associated namespaces and classes are the namespace in which the template is defined; for member templates, the member template's class; the namespaces and classes associated with the types of the template arguments provided for template type parameters (excluding template template parameters); the namespaces in which any template template arguments are defined; and the classes in which any member templates used as template template arguments are defined. [Note: non-type template arguments do not contribute to the set of associated namespaces. ]
There is a problem with the term "is a template-id". template-id is a syntactic construct and you can't really talk about a type being a template-id. Presumably, this is intended to mean "If T is the type of a class template specialization ...".

Proposed Resolution (October 2003):

In 6.5.4 [basic.lookup.argdep], paragraph 2, bullet 8, replace

If T is a template-id ...
with
If T is a class template specialization ...




557. Does argument-dependent lookup cause template instantiation?

Section: 6.5.4  [basic.lookup.argdep]     Status: CD1     Submitter: Mike Miller     Date: 8 February 2006

[Voted into WP at the October, 2006 meeting.]

One might assume from 13.9.2 [temp.inst] paragraph 1 that argument-dependent lookup would require instantiation of any class template specializations used in argument types:

Unless a class template specialization has been explicitly instantiated (13.9.3 [temp.explicit]) or explicitly specialized (13.9.4 [temp.expl.spec]), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.

A complete class type is required to determine the associated classes and namespaces for the argument type (to determine the class's bases) and to determine the friend functions declared by the class, so the completeness of the class type certainly “affects the semantics of the program.”

This conclusion is reinforced by the second bullet of 6.5.4 [basic.lookup.argdep] paragraph 2:

A class template specialization is a class type, so the second bullet would appear to apply, requiring the specialization to be instantiated in order to determine its base classes.

However, bullet 8 of that paragraph deals explicitly with class template specializations:

Note that the class template specialization itself is not listed as an associated class, unlike other class types, and there is no mention of base classes. If bullet 8 were intended as a supplement to the treatment of class types in bullet 2, one would expect phrasing along the lines of, “In addition to the associated namespaces and classes for all class types...” or some such; instead, bullet 8 reads like a self-contained and complete specification.

If argument-dependent lookup does not cause implicit instantiation, however, examples like the following fail:

    template <typename T> class C {
        friend void f(C<T>*) { }
    };
    void g(C<int>* p) {
        f(p);    // found by ADL??
    }

Implementations differ in whether this example works or not.

Proposed resolution (April, 2006):

  1. Change bullet 2 of 6.5.4 [basic.lookup.argdep] paragraph 2 as indicated:

  2. Delete bullet 8 of 6.5.4 [basic.lookup.argdep] paragraph 2:




298. T::x when T is cv-qualified

Section: 6.5.5.2  [class.qual]     Status: CD1     Submitter: Steve Adamczyk     Date: 7 Jul 2001

[Voted into WP at April 2003 meeting.]

Can a typedef T to a cv-qualified class type be used in a qualified name T::x?

    struct A { static int i; };
    typedef const A CA;
    int main () {
      CA::i = 0;  // Okay?
    }

Suggested answer: Yes. All the compilers I tried accept the test case.

Proposed resolution (10/01):

In 6.5.5.2 [class.qual] paragraph 1 add the indicated text:

If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-name-specifier is looked up in the scope of the class (6.5.2 [class.member.lookup]), except for the cases listed below. The name shall represent one or more members of that class or of one of its base classes (11.7 [class.derived]). If the class-or-namespace-name of the nested-name-specifier names a cv-qualified class type, it nominates the underlying class (the cv-qualifiers are ignored).

Notes from 4/02 meeting:

There is a problem in that class-or-namespace-name does not include typedef names for cv-qualified class types. See 9.2.4 [dcl.typedef] paragraph 4:

Argument and text removed from proposed resolution (October 2002):

9.2.4 [dcl.typedef] paragraph 5:

Here's a good question: in this example, should X be used as a name-for-linkage-purposes (FLP name)?

  typedef class { } const X;

Because a type-qualifier is parsed as a decl-specifier, it isn't possible to declare cv-qualified and cv-unqualified typedefs for a type in a single declaration. Also, of course, there's no way to declare a typedef for the cv-unqualified version of a type for which only a cv-qualified version has a name. So, in the above example, if X isn't used as the FLP name, then there can be no FLP name. Also note that a FLP name usually represents a parameter type, where top-level cv-qualifiers are usually irrelevant anyway.

Data points: for the above example, Microsoft uses X as the FLP name; GNU and EDG do not.

My recommendation: for consistency with the direction we're going on this issue, for simplicity of description (e.g., "the first class-name declared by the declaration"), and for (very slightly) increased utility, I think Microsoft has this right.

If the typedef declaration defines an unnamed class type (or enum type), the first typedef-name declared by the declaration to be have that class type (or enum type) or a cv-qualified version thereof is used to denote the class type (or enum type) for linkage purposes only (6.6 [basic.link]). [Example: ...

Proposed resolution (October 2002):

6.5.6 [basic.lookup.elab] paragraphs 2 and 3:

This sentence is deleted twice:

... If this name lookup finds a typedef-name, the elaborated-type-specifier is ill-formed. ...

Note that the above changes are included in N1376 as part of the resolution of issue 245.

_N4567_.5.1.1 [expr.prim.general] paragraph 7:

This is only a note, and it is at least incomplete (and quite possibly inaccurate), despite (or because of) its complexity. I propose to delete it.

... [Note: a typedef-name that names a class is a class-name (11.3 [class.name]). Except as the identifier in the declarator for a constructor or destructor definition outside of a class member-specification (11.4.5 [class.ctor], 11.4.7 [class.dtor]), a typedef-name that names a class may be used in a qualified-id to refer to a constructor or destructor. ]

9.2.4 [dcl.typedef] paragraph 4:

My first choice would have been to make this the primary statement about the equivalence of typedef-name and class-name, since the equivalence comes about as a result of a typedef declaration. Unfortunately, references to class-name point to 11.3 [class.name], so it would seem that the primary statement should be there instead. To avoid the possiblity of conflicts in the future, I propose to make this a note.

[Note: A typedef-name that names a class type, or a cv-qualified version thereof, is also a class-name (11.3 [class.name]). If a typedef-name is used following the class-key in an elaborated-type-specifier (9.2.9.4 [dcl.type.elab]), or in the class-head of a class declaration (Clause 11 [class]), or is used as the identifier in the declarator for a constructor or destructor declaration (11.4.5 [class.ctor], 11.4.7 [class.dtor]), to identify the subject of an elaborated-type-specifier (9.2.9.4 [dcl.type.elab]), class declaration (Clause 11 [class]), constructor declaration (11.4.5 [class.ctor]), or destructor declaration (11.4.7 [class.dtor]), the program is ill-formed. ] [Example: ...

9.2.9.4 [dcl.type.elab] paragraph 2:

This is the only remaining (normative) statement that a typedef-name can't be used in an elaborated-type-specifier. The reference to template type-parameter is deleted by the resolution of issue 283.

... If the identifier resolves to a typedef-name or a template type-parameter, the elaborated-type-specifier is ill-formed. [Note: ...

9.3 [dcl.decl] grammar rule declarator-id:

When I looked carefully into the statement of the rule prohibiting a typedef-name in a constructor declaration, it appeared to me that this grammar rule (inadvertently?) allows something that's always forbidden semantically.

11.3 [class.name] paragraph 5:

Unlike the prohibitions against appearing in an elaborated-type-specifier or constructor or destructor declarator, each of which was expressed more than once, the prohibition against a typedef-name appearing in a class-head was previously stated only in 9.2.4 [dcl.typedef]. It seems to me that that prohibition belongs here instead. Also, it seems to me important to clarify that a typedef-name that is a class-name is still a typedef-name. Otherwise, the various prohibitions can be argued around easily, if perversely ("But that isn't a typedef-name, it's a class-name; it says so right there in 11.3 [class.name].")

A typedef-name (9.2.4 [dcl.typedef]) that names a class type or a cv-qualified version thereof is also a class-name, but shall not be used in an elaborated-type-specifier; see also 9.2.4 [dcl.typedef]. as the identifier in a class-head.

11.4.5 [class.ctor] paragraph 3:

The new nonterminal references are needed to really nail down what we're talking about here. Otherwise, I'm just eliminating redundancy. (A typedef-name that doesn't name a class type is no more valid here than one that does.)

A typedef-name that names a class is a class-name (9.2.4 [dcl.typedef]); however, a A typedef-name that names a class shall not be used as the identifier class-name in the declarator declarator-id for a constructor declaration.

11.4.7 [class.dtor] paragraph 1:

The same comments apply here as to 11.4.5 [class.ctor].

... A typedef-name that names a class is a class-name (7.1.3); however, a A typedef-name that names a class shall not be used as the identifier class-name following the ~ in the declarator for a destructor declaration.



318. struct A::A should not name the constructor of A

Section: 6.5.5.2  [class.qual]     Status: CD1     Submitter: John Spicer     Date: 18 Oct 2001

[Voted into WP at April 2003 meeting.]

A use of an injected-class-name in an elaborated-type-specifier should not name the constructor of the class, but rather the class itself, because in that context we know that we're looking for a type. See issue 147.

Proposed Resolution (revised October 2002):

This clarifies the changes made in the TC for issue 147.

In 6.5.5.2 [class.qual] paragraph 1a replace:

If the nested-name-specifier nominates a class C, and the name specified after the nested-name-specifier, when looked up in C, is the injected class name of C (Clause 11 [class]), the name is instead considered to name the constructor of class C.

with

In a lookup in which the constructor is an acceptable lookup result, if the nested-name-specifier nominates a class C and the name specified after the nested-name-specifier, when looked up in C, is the injected class name of C (Clause 11 [class]), the name is instead considered to name the constructor of class C. [Note: For example, the constructor is not an acceptable lookup result in an elaborated type specifier so the constructor would not be used in place of the injected class name.]

Note that issue 263 updates a part of the same paragraph.

Append to the example:

  struct A::A a2;  // object of type A



400. Using-declarations and the "struct hack"

Section: 6.5.5.3  [namespace.qual]     Status: CD1     Submitter: Mark Mitchell     Date: 22 Jan 2003

[Voted into WP at March 2004 meeting.]

Consider this code:

  struct A { int i; struct i {}; };
  struct B { int i; struct i {}; };
  struct D : public A, public B { using A::i; void f (); };
  void D::f () { struct i x; }

I can't find anything in the standard that says definitively what this means. 9.9 [namespace.udecl] says that a using-declaration shall name "a member of a base class" -- but here we have two members, the data member A::i and the class A::i.

Personally, I'd find it more attractive if this code did not work. I'd like "using A::i" to mean "lookup A::i in the usual way and bind B::i to that", which would mean that while "i = 3" would be valid in D::f, "struct i x" would not be. However, if there were no A::i data member, then "A::i" would find the struct and the code in D::f would be valid.

John Spicer: I agree with you, but unfortunately the standard committee did not.

I remembered that this was discussed by the committee and that a resolution was adopted that was different than what I hoped for, but I had a hard time finding definitive wording in the standard.

I went back though my records and found the paper that proposed a resolution and the associated committee motion that adopted the proposed resolution The paper is N0905, and "option 1" from that paper was adopted at the Stockholm meeting in July of 1996. The resolution is that "using A::i" brings in everything named i from A.

6.5.5.3 [namespace.qual] paragraph 2 was modified to implement this resolution, but interestingly that only covers the namespace case and not the class case. I think the class case was overlooked when the wording was drafted. A core issue should be opened to make sure the class case is handled properly.

Notes from April 2003 meeting:

This is related to issue 11. 9.9 [namespace.udecl] paragraph 10 has an example for namespaces.

Proposed resolution (October 2003):

Add a bullet to the end of 6.5.5.2 [class.qual] paragraph 1:

Change the beginning of 9.9 [namespace.udecl] paragraph 4 from

A using-declaration used as a member-declaration shall refer to a member of a base class of the class being defined, shall refer to a member of an anonymous union that is a member of a base class of the class being defined, or shall refer to an enumerator for an enumeration type that is a member of a base class of the class being defined.

to

In a using-declaration used as a member-declaration, the nested-name-specifier shall name a base class of the class being defined. Such a using-declaration introduces the set of declarations found by member name lookup (6.5.2 [class.member.lookup], 6.5.5.2 [class.qual]).



245. Name lookup in elaborated-type-specifiers

Section: 6.5.6  [basic.lookup.elab]     Status: CD1     Submitter: Jack Rouse     Date: 14 Sep 2000

[Voted into WP at April 2003 meeting.]

I have some concerns with the description of name lookup for elaborated type specifiers in 6.5.6 [basic.lookup.elab]:

  1. Paragraph 2 has some parodoxical statements concerning looking up names that are simple identifers:

    If the elaborated-type-specifier refers to an enum-name and this lookup does not find a previously declared enum-name, the elaborated-type-specifier is ill-formed. If the elaborated-type-specifier refers to an [sic] class-name and this lookup does not find a previously declared class-name... the elaborated-type-specifier is a declaration that introduces the class-name as described in 6.4.2 [basic.scope.pdecl]."

    It is not clear how an elaborated-type-specifier can refer to an enum-name or class-name given that the lookup does not find such a name and that class-name and enum-name are not part of the syntax of an elaborated-type-specifier.

  2. The second sentence quoted above seems to suggest that the name found will not be used if it is not a class name. typedef-name names are ill-formed due to the sentence preceding the quote. If lookup finds, for instance, an enum-name then a new declaration will be created. This differs from C, and from the enum case, and can have surprising effects:

        struct S {
           enum E {
               one = 1
           };
           class E* p;     // declares a global class E?
        };
    

    Was this really the intent? If this is the case then some more work is needed on 6.5.6 [basic.lookup.elab]. Note that the section does not make finding a type template formal ill-formed, as is done in 9.2.9.4 [dcl.type.elab]. I don't see anything that makes a type template formal name a class-name. So the example in 9.2.9.4 [dcl.type.elab] of friend class T; where T is a template type formal would no longer be ill-formed with this interpretation because it would declare a new class T.

(See also issue 254.)

Notes from the 4/02 meeting:

This will be consolidated with the changes for issue 254. See also issue 298.

Proposed resolution (October 2002):

As given in N1376=02-0034. Note that the inserts and strikeouts in that document do not display correctly in all browsers; <del> --> <strike> and <ins> --> <b>, and the similar changes for the closing delimiters, seem to do the trick.




254. Definitional problems with elaborated-type-specifiers

Section: 6.5.6  [basic.lookup.elab]     Status: CD1     Submitter: Clark Nelson     Date: 26 Oct 2000

[Voted into WP at April 2003 meeting.]

  1. The text in 6.5.6 [basic.lookup.elab] paragraph 2 twice refers to the possibility that an elaborated-type-specifier might have the form

            class-key identifier ;
    

    However, the grammar for elaborated-type-specifier does not include a semicolon.

  2. In both 6.5.6 [basic.lookup.elab] and 9.2.9.4 [dcl.type.elab], the text asserts that an elaborated-type-specifier that refers to a typedef-name is ill-formed. However, it is permissible for the form of elaborated-type-specifier that begins with typename to refer to a typedef-name.

    This problem is the result of adding the typename form to the elaborated-type-name grammar without changing the verbiage correspondingly. It could be fixed either by updating the verbiage or by moving the typename syntax into its own production and referring to both nonterminals when needed.

(See also issue 180. If this issue is resolved in favor of a separate nonterminal in the grammar for the typename forms, the wording in that issue's resolution must be changed accordingly.)

Notes from 04/01 meeting:

The consensus was in favor of moving the typename forms out of the elaborated-type-specifier grammar.

Notes from the 4/02 meeting:

This will be consolidated with the changes for issue 245.

Proposed resolution (October 2002):

As given in N1376=02-0034.




216. Linkage of nameless class-scope enumeration types

Section: 6.6  [basic.link]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 13 Mar 2000

[Moved to DR at 10/01 meeting.]

6.6 [basic.link] paragraph 4 says (among other things):
A name having namespace scope has external linkage if it is the name of
That prohibits for example:
    typedef enum { e1 } *PE;
    void f(PE) {}  // Cannot declare a function (with linkage) using a
		   // type with no linkage.

However, the same prohibition was not made for class scope types. Indeed, 6.6 [basic.link] paragraph 5 says:

In addition, a member function, static data member, class or enumeration of class scope has external linkage if the name of the class has external linkage.

That allows for:

    struct S {
       typedef enum { e1 } *MPE;
       void mf(MPE) {}
    };

My guess is that this is an unintentional consequence of 6.6 [basic.link] paragraph 5, but I would like confirmation on that.

Proposed resolution:

Change text in 6.6 [basic.link] paragraph 5 from:

In addition, a member function, static data member, class or enumeration of class scope has external linkage if the name of the class has external linkage.
to:
In addition, a member function, a static data member, a named class or enumeration of class scope, or an unnamed class or enumeration defined in a class-scope typedef declaration such that the class or enumeration has the typedef name for linkage purposes (9.2.4 [dcl.typedef]), has external linkage if the name of the class has external linkage.



319. Use of names without linkage in declaring entities with linkage

Section: 6.6  [basic.link]     Status: CD1     Submitter: Clark Nelson     Date: 29 Oct 2001

[Voted into WP at October 2004 meeting.]

According to 6.6 [basic.link] paragraph 8, "A name with no linkage ... shall not be used to declare an entity with linkage." This would appear to rule out code such as:

  typedef struct {
    int i;
  } *PT;
  extern "C" void f(PT);
[likewise]
  static enum { a } e;
which seems rather harmless to me.

See issue 132, which dealt with a closely related issue.

Andrei Iltchenko submitted the same issue via comp.std.c++ on 17 Dec 2001:

Paragraph 8 of Section 6.6 [basic.link] contains the following sentences: "A name with no linkage shall not be used to declare an entity with linkage. If a declaration uses a typedef name, it is the linkage of the type name to which the typedef refers that is considered."

The problem with this wording is that it doesn't cover cases where the type to which a typedef-name refers has no name. As a result it's not clear whether, for example, the following program is well-formed:

#include <vector>

int  main()
{
   enum  {   sz = 6u   };
   typedef int  (* aptr_type)[sz];
   typedef struct  data  {
      int   i,  j;
   }  * elem_type;
   std::vector<aptr_type>   vec1;
   std::vector<elem_type>   vec2;
}

Suggested resolution:

My feeling is that the rules for whether or not a typedef-name used in a declaration shall be treated as having or not having linkage ought to be modelled after those for dependent types, which are explained in 13.8.3.2 [temp.dep.type].

Add the following text at the end of Paragraph 8 of Section 6.6 [basic.link] and replace the following example:

In case of the type referred to by a typedef declaration not having a name, the newly declared typedef-name has linkage if and only if its referred type comprises no names of no linkage excluding local names that are eligible for appearance in an integral constant-expression (7.7 [expr.const]). [Note: if the referred type contains a typedef-name that does not denote an unnamed class, the linkage of that name is established by the recursive application of this rule for the purposes of using typedef names in declarations.] [Example:
  void f()
  {
     struct A { int x; };        // no linkage
     extern A a;                 // ill-formed
     typedef A Bl
     extern B b;                 // ill-formed

     enum  {   sz = 6u   };
     typedef int  (* C)[sz];     // C has linkage because sz can
                                 // appear in a constant expression
  }
--end example.]

Additional issue (13 Jan 2002, from Andrei Iltchenko):

Paragraph 2 of Section 13.4.2 [temp.arg.type] is inaccurate and unnecessarily prohibits a few important cases; it says "A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template-parameter." The inaccuracy stems from the fact that it is not a type but its name that can have a linkage.

For example based on the current wording of 13.4.2 [temp.arg.type], the following example is ill-formed.

  #include <vector>
  struct  data  {
    int   i,  j;
  };
  int  main()
  {
    enum  {   sz = 6u   };
    std::vector<int(*)[sz]>   vec1; // The types 'int(*)[sz]' and 'data*'
    std::vector<data*>        vec2; // have no names and are thus illegal
                                    // as template type arguments.
  }

Suggested resolution:

Replace the whole second paragraph of Section 13.4.2 [temp.arg.type] with the following wording:

A type whose name does not have a linkage or a type compounded from any such type shall not be used as a template-argument for a template-parameter. In case of a type T used as a template type argument not having a name, T constitutes a valid template type argument if and only if the name of an invented typedef declaration referring to T would have linkage; see 3.5. [Example:
  template <class T> class X { /* ... */ };
  void f()
  {
    struct S { /* ... */ };
    enum  {   sz = 6u   };

    X<S> x3;                     // error: a type name with no linkage
                                 // used as template-argument
    X<S*> x4;                    // error: pointer to a type name with
                                 // no linkage used as template-argument
    X<int(*)[sz]> x5;            // OK: since the name of typedef int
                                 // (*pname)[sz] would have linkage
  }
--end example] [Note: a template type argument may be an incomplete type (6.8 [basic.types]).]

Proposed resolution:

This is resolved by the changes for issue 389. The present issue was moved back to Review status in February 2004 because 389 was moved back to Review.




389. Unnamed types in entities with linkage

Section: 6.6  [basic.link]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 31 Oct 2002

[Voted into WP at October 2004 meeting.]

6.6 [basic.link] paragraph 8 says (among other things):

A name with no linkage (notably, the name of a class or enumeration declared in a local scope (6.4.3 [basic.scope.block])) shall not be used to declare an entity with linkage. If a declaration uses a typedef name, it is the linkage of the type name to which the typedef refers that is considered.

I would expect this to catch situations such as the following:

  // File 1:
  typedef struct {} *UP;
  void f(UP) {}

  // File 2:
  typedef struct {} *UP; // Or: typedef struct {} U, *UP;
  void f(UP);

The problem here is that most implementations must generate the same mangled name for "f" in two translation units. The quote from the standard above isn't quite clear, unfortunately: There is no type name to which the typedef refers.

A related situation is the following:

  enum { no, yes } answer;
The variable "answer" is declared as having external linkage, but it is declared with an unnamed type. Section 6.6 [basic.link] talks about the linkage of names, however, and does therefore not prohibit this. There is no implementation issue for most compilers because they do not ordinarily mangle variable names, but I believe the intent was to allow that implementation technique.

Finally, these problems are much less relevant when declaring names with internal linkage. For example, I would expect there to be few problems with:

  typedef struct {} *UP;
  static void g(UP);

I recently tried to interpret 6.6 [basic.link] paragraph 8 with the assumption that types with no names have no linkage. Surprisingly, this resulted in many diagnostics on variable declarations (mostly like "answer" above).

I'm pretty sure the standard needs clarifying words in this matter, but which way should it go?

See also issue 319.

Notes from April 2003 meeting:

There was agreement that this check is not needed for variables and functions with extern "C" linkage, and a change there is desirable to allow use of legacy C headers. The check is also not needed for entities with internal linkage, but there was no strong sentiment for changing that case.

We also considered relaxing this requirement for extern "C++" variables but decided that we did not want to change that case.

We noted that if extern "C" functions are allowed an additional check is needed when such functions are used as arguments in calls of function templates. Deduction will put the type of the extern "C" function into the type of the template instance, i.e., there would be a need to mangle the name of an unnamed type. To plug that hole we need an additional requirement on the template created in such a case.

Proposed resolution (April 2003, revised slightly October 2003 and March 2004):

In 6.6 [basic.link] paragraph 8, change

A name with no linkage (notably, the name of a class or enumeration declared in a local scope (6.4.3 [basic.scope.block])) shall not be used to declare an entity with linkage. If a declaration uses a typedef name, it is the linkage of the type name to which the typedef refers that is considered.

to

A type is said to have linkage if and only if A type without linkage shall not be used as the type of a variable or function with linkage, unless the variable or function has extern "C" linkage (9.11 [dcl.link]). [Note: in other words, a type without linkage contains a class or enumeration that cannot be named outside of its translation unit. An entity with external linkage declared using such a type could not correspond to any other entity in another translation unit of the program and is thus not permitted. Also note that classes with linkage may contain members whose types do not have linkage, and that typedef names are ignored in the determination of whether a type has linkage.]

Change 13.4.2 [temp.arg.type] paragraph 2 from (note: this is the wording as updated by issue 62)

The following types shall not be used as a template-argument for a template type-parameter:

to

A type without linkage (6.6 [basic.link]) shall not be used as a template-argument for a template type-parameter.

Once this issue is ready, issue 319 should be moved back to ready as well.




474. Block-scope extern declarations in namespace members

Section: 6.6  [basic.link]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 23 Jul 2004

[Voted into WP at October 2005 meeting.]

Consider the following bit of code:

    namespace N {
      struct S {
        void f();
      };
    }
    using namespace N;
    void S::f() {
      extern void g();  // ::g or N::g?
    }

In 6.6 [basic.link] paragraph 7 the Standard says (among other things),

When a block scope declaration of an entity with linkage is not found to refer to some other declaration, then that entity is a member of the innermost enclosing namespace.

The question then is whether N is an “enclosing namespace” for the local declaration of g()?

Proposed resolution (October 2004):

Add the following text as a new paragraph at the end of 9.8.2 [namespace.def]:

The enclosing namespaces of a declaration are those namespaces in which the declaration lexically appears, except for a redeclaration of a namespace member outside its original namespace (e.g., a definition as specified in _N4868_.9.8.2.3 [namespace.memdef]). Such a redeclaration has the same enclosing namespaces as the original declaration. [Example:
  namespace Q {
    namespace V {
      void f(); // enclosing namespaces are the global namespace, Q, and Q::V
      class C { void m(); };
    }
    void V::f() { // enclosing namespaces are the global namespace, Q, and Q::V
      extern void h(); // ... so this declares Q::V::h
    }
    void V::C::m() { // enclosing namespaces are the global namespace, Q, and Q::V
    }
  }

end example]




513. Non-class “most-derived” objects

Section: 6.7.2  [intro.object]     Status: CD1     Submitter: Marc Schoolderman     Date: 20 Mar 2005

[Voted into WP at April, 2006 meeting.]

The standard uses “most derived object” in some places (for example, Clause 3 [intro.defs] “dynamic type,” 7.6.2.9 [expr.delete]) to refer to objects of both class and non-class type. However, 6.7.2 [intro.object] only formally defines it for objects of class type.

Possible fix: Change the wording in 6.7.2 [intro.object] paragraph 4 from

an object of a most derived class type is called a most derived object

to

an object of a most derived class type, or of non-class type, is called a most derived object

Proposed resolution (October, 2005):

Add the indicated words to 6.7.2 [intro.object] paragraph 4:

If a complete object, a data member (11.4 [class.mem]), 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 a most derived object.



119. Object lifetime and aggregate initialization

Section: 6.7.3  [basic.life]     Status: CD1     Submitter: Jack Rouse     Date: 20 May 1999

[Moved to DR at 4/02 meeting.]

Jack Rouse: 6.7.3 [basic.life] paragraph 1 includes:

The lifetime of an object is a runtime property of the object. The lifetime of an object of type T begins when:
Consider the code:
    struct B {
        B( int = 0 );
        ~B();
    };

    struct S {
        B b1;
    };

    int main()
    {
        S s = { 1 };
        return 0;
    }
In the code above, class S does have a non-trivial constructor, the default constructor generated by the compiler. According the text above, the lifetime of the auto s would never begin because a constructor for S is never called. I think the second case in the text needs to include aggregate initialization.

Mike Miller: I see a couple of ways of fixing the problem. One way would be to change "the constructor call has completed" to "the object's initialization is complete."

Another would be to add following "a class type with a non-trivial constructor" the phrase "that is not initialized with the brace notation (9.4.2 [dcl.init.aggr] )."

The first formulation treats aggregate initialization like a constructor call; even POD-type members of an aggregate could not be accessed before the aggregate initialization completed. The second is less restrictive; the POD-type members of the aggregate would be usable before the initialization, and the members with non-trivial constructors (the only way an aggregate can acquire a non-trivial constructor) would be protected by recursive application of the lifetime rule.

Proposed resolution (04/01):

In 6.7.3 [basic.life] paragraph 1, change

If T is a class type with a non-trivial constructor (11.4.5 [class.ctor]), the constructor call has completed.

to

If T is a class type with a non-trivial constructor (11.4.5 [class.ctor]), the initialization is complete. [Note: the initialization can be performed by a constructor call or, in the case of an aggregate with an implicitly-declared non-trivial default constructor, an aggregate initialization (9.4.2 [dcl.init.aggr]).]



274. Cv-qualification and char-alias access to out-of-lifetime objects

Section: 6.7.3  [basic.life]     Status: CD1     Submitter: Mike Miller     Date: 14 Mar 2001

[Voted into WP at April 2003 meeting.]

The wording in 6.7.3 [basic.life] paragraph 6 allows an lvalue designating an out-of-lifetime object to be used as the operand of a static_cast only if the conversion is ultimately to "char&" or "unsigned char&". This description excludes the possibility of using a cv-qualified version of these types for no apparent reason.

Notes on 04/01 meeting:

The wording should be changed to allow cv-qualified char types.

Proposed resolution (04/01):

In 6.7.3 [basic.life] paragraph 6 change the third bullet:

to read:




404. Unclear reference to construction with non-trivial constructor

Section: 6.7.3  [basic.life]     Status: CD1     Submitter: Mike Miller     Date: 8 Apr 2003

[Voted into WP at March 2004 meeting.]

6.7.3 [basic.life] paragraph 1 second bullet says:

if T is a class type with a non-trivial constructor (12.1), the constructor call has completed.

This is confusing; what was intended is probably something like

if T is a class type and the constructor invoked to create the object is non-trivial (12.1), the constructor call has completed.

Proposed Resolution (October 2003):

As given above.




594. Coordinating issues 119 and 404 with delegating constructors

Section: 6.7.3  [basic.life]     Status: CD1     Submitter: Tom Plum     Date: 30 August 2006

[Voted into the WP at the September, 2008 meeting.]

In ISO/IEC 14882:2003, the second bullet of 6.7.3 [basic.life] paragraph 1 reads,

if T is a class type with a non-trivial constructor (11.4.5 [class.ctor]), the constructor call has completed.

Issue 119 pointed out that aggregate initialization can be used with some classes with a non-trivial implicitly-declared default constructor, and that in such cases there is no call to the object's constructor. The resolution for that issue was to change the previously-cited wording to read,

If T is a class type with a non-trivial constructor (11.4.5 [class.ctor], the initialization is complete.

Later (but before the WP was revised with the wording from the resolution of issue 119), issue 404 changed the 2003 wording to read,

If T is a class type and the constructor invoked to create the object is non-trivial (11.4.5 [class.ctor]), the constructor call has completed.

thus reversing the effect of issue 119, whose whole purpose was to cover objects with non-trivial constructors that are not invoked.

Through an editorial error, the post-Redmond draft (N1905) still contained the original 2003 wording that should have been replaced by the resolution of issue 119, in addition to the new wording from the resolution:

if T is a class type and the constructor invoked to create the object is non-trivial (11.4.5 [class.ctor]), the constructor call has completed. the initialization is complete.

Finally, during the application of the edits for delegating constructors (N1986), this editing error was “fixed” by retaining the original 2003 wording (which was needed for the application of the change specified in N1986), so that the current draft (N2009) reads,

if T is a class type and the constructor invoked to create the object is non-trivial (11.4.5 [class.ctor]), the principal constructor call 11.9.3 [class.base.init]) has completed.

Because the completion of the call to the principal constructor corresponds to the point at which the object is “fully constructed” (14.3 [except.ctor] paragraph 2), i.e., its initialization is complete, I believe that the exact wording of the issue 119 resolution would be correct and should be restored verbatim.

Proposed resolution (June, 2008):

Change 6.7.3 [basic.life] paragraph 1 as follows:

The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [Note: Initialization by a trivial copy constructor is non-trivial initialization. —end note] The lifetime of an object of type T begins when:

The lifetime of an object of type T ends when...




521. Requirements for exceptions thrown by allocation functions

Section: 6.7.5.5.2  [basic.stc.dynamic.allocation]     Status: CD1     Submitter: Alisdair Meredith     Date: 22 May 2005

[Voted into WP at the October, 2006 meeting.]

According to 6.7.5.5.2 [basic.stc.dynamic.allocation] paragraph 3,

Any other allocation function that fails to allocate storage shall only indicate failure by throwing an exception of class std::bad_alloc (17.6.4.1 [bad.alloc]) or a class derived from std::bad_alloc.

Shouldn't this statement have the usual requirements for an unambiguous and accessible base class?

Proposed resolution (April, 2006):

Change the last sentence of 6.7.5.5.2 [basic.stc.dynamic.allocation] paragraph 3 as indicated:

Any other allocation function that fails to allocate storage shall only indicate failure only by throwing an exception of class std::bad_alloc (17.6.4.1 [bad.alloc]) or a class derived from std::bad_alloc a type that would match a handler (14.4 [except.handle]) of type std::bad_alloc (17.6.4.1 [bad.alloc]).



220. All deallocation functions should be required not to throw

Section: 6.7.5.5.3  [basic.stc.dynamic.deallocation]     Status: CD1     Submitter: Herb Sutter     Date: 31 Mar 2000

[Voted into the WP at the September, 2008 meeting (resolution in paper N2757).]

[Picked up by evolution group at October 2002 meeting.]

The default global operators delete are specified to not throw, but there is no requirement that replacement global, or class-specific, operators delete must not throw. That ought to be required.

In particular:

We already require that all versions of an allocator's deallocate() must not throw, so that part is okay.

Rationale (04/00):

  1. Replacement deallocation functions are already required not to throw an exception (cf 16.4.5.8 [res.on.functions] paragraph 2, as applied to 17.6.3.2 [new.delete.single] paragraph 12 and 17.6.3.3 [new.delete.array] paragraph 11).
  2. Section 16.4.5.6 [replacement.functions] is describing the signatures of the functions to be replaced; exception specfications are not part of the signature.
  3. There does not appear to be any pressing need to require that class member deallocation functions not throw.

Note (March, 2008):

The Evolution Working Group has accepted the intent of this issue and referred it to CWG for action for C++0x (see paper J16/07-0033 = WG21 N2173).

Proposed resolution (March, 2008):

Change 6.7.5.5.3 [basic.stc.dynamic.deallocation] paragraph 3 as follows:

A deallocation function shall not terminate by throwing an exception. The value of the first argument supplied to a deallocation function...



348. delete and user-written deallocation functions

Section: 6.7.5.5.3  [basic.stc.dynamic.deallocation]     Status: CD1     Submitter: Ruslan Abdikeev     Date: 1 April 2002

[Voted into WP at October 2005 meeting.]

Standard is clear on behaviour of default allocation/deallocation functions. However, it is surpisingly vague on requirements to the behaviour of user-defined deallocation function and an interaction between delete-expression and deallocation function. This caused a heated argument on fido7.su.c-cpp newsgroup.

Resume:

It is not clear if user-supplied deallocation function is called from delete-expr when the operand of delete-expr is the null pointer (7.6.2.9 [expr.delete]). If it is, standard does not specify what user-supplied deallocation function shall do with the null pointer operand (17.6.3 [new.delete]). Instead, Standard uses the term "has no effect", which meaning is too vague in context given (7.6.2.9 [expr.delete]).

Description:

Consider statements

   char* p= 0; //result of failed non-throwing ::new char[]
   ::delete[] p;
Argument passed to delete-expression is valid - it is the result of a call to the non-throwing version of ::new, which has been failed. 7.6.2.9 [expr.delete] paragraph 1 explicitly prohibit us to pass 0 without having the ::new failure.

Standard does NOT specify whether user-defined deallocation function should be called in this case, or not.

Specifically, standard says in 7.6.2.9 [expr.delete] paragraph 2:

...if the value of the operand of delete is the null pointer the operation has no effect.
Standard doesn't specify term "has no effect". It is not clear from this context, whether the called deallocation function is required to have no effect, or delete-expression shall not call the deallocation function.

Furthermore, in para 4 standard says on default deallocation function:

If the delete-expression calls the implementation deallocation function (6.7.5.5.3 [basic.stc.dynamic.deallocation]), if the operand of the delete expression is not the null pointer constant, ...
Why it is so specific on interaction of default deallocation function and delete-expr?

If "has no effect" is a requirement to the deallocation function, then it should be stated in 6.7.5.5.3 [basic.stc.dynamic.deallocation], or in 17.6.3.2 [new.delete.single] and 17.6.3.3 [new.delete.array], and it should be stated explicitly.

Furthermore, standard does NOT specify what actions shall be performed by user-supplied deallocation function if NULL is given (17.6.3.2 [new.delete.single] paragraph 12):

Required behaviour: accept a value of ptr that is null or that was returned by an earlier call to the default operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&).

The same corresponds to ::delete[] case.

Expected solution:

  1. Make it clear that delete-expr will not call deallocation function if null pointer is given (in 7.6.2.9 [expr.delete]).
  2. Specify what user deallocation function shall do when null is given (either in 6.7.5.5.3 [basic.stc.dynamic.deallocation], or in 17.6.3.2 [new.delete.single], and 17.6.3.3 [new.delete.array]).

Notes from October 2002 meeting:

We believe that study of 17.6.3.2 [new.delete.single] paragraphs 12 and 13, 17.6.3.3 [new.delete.array] paragraphs 11 and 12, and 6.7.5.5.3 [basic.stc.dynamic.deallocation] paragraph 3 shows that the system-provided operator delete functions must accept a null pointer and ignore it. Those sections also show that a user-written replacement for the system-provided operator delete functions must accept a null pointer. There is no requirement that such functions ignore a null pointer, which is okay -- perhaps the reason for replacing the system-provided functions is to do something special with null pointer values (e.g., log such calls and return).

We believe that the standard should not require an implementation to call a delete function with a null pointer, but it must allow that. For the system-provided delete functions or replacements thereof, the standard already makes it clear that the delete function must accept a null pointer. For class-specific delete functions, we believe the standard should require that such functions accept a null pointer, though it should not mandate what they do with null pointers.

7.6.2.9 [expr.delete] needs to be updated to say that it is unspecified whether or not the operator delete function is called with a null pointer, and 6.7.5.5.3 [basic.stc.dynamic.deallocation] needs to be updated to say that any deallocation function must accept a null pointer.

Proposed resolution (October, 2004):

  1. Change 7.6.2.9 [expr.delete] paragraph 2 as indicated:

    If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. In either alternative, if the value of the operand of delete is the null pointer the operation has no effect may be a null pointer value. If it is not a null pointer value, in In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (6.7.2 [intro.object]) representing a base class of such an object (11.7 [class.derived])...
  2. Change 7.6.2.9 [expr.delete] paragraph 4 as follows (note that the old wording reflects the changes proposed by issue 442:

    The cast-expression in a delete-expression shall be evaluated exactly once. If the delete-expression calls the implementation deallocation function (6.7.5.5.3 [basic.stc.dynamic.deallocation]), and if the value of the operand of the delete expression is not a null pointer, the deallocation function will deallocate the storage referenced by the pointer thus rendering the pointer invalid. [Note: the value of a pointer that refers to deallocated storage is indeterminate. —end note]

  3. Change 7.6.2.9 [expr.delete] paragraphs 6-7 as follows:

    The If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 11.9.3 [class.base.init]).

    The If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function (6.7.5.5.3 [basic.stc.dynamic.deallocation]). Otherwise, it is unspecified whether the deallocation function will be called. [Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception. —end note]

  4. Change 6.7.5.5.3 [basic.stc.dynamic.deallocation] paragraph 3 as indicated:

    The value of the first argument supplied to one of the a deallocation functions provided in the standard library may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

[Note: this resolution also resolves issue 442.]




649. Optionally ill-formed extended alignment requests

Section: 6.7.6  [basic.align]     Status: CD1     Submitter: Mike Miller     Date: 12 Aug 2007

[Voted into the WP at the September, 2008 meeting.]

The requirements on an implementation when presented with an alignment-specifier not supported by that implementation in that context are contradictory: 6.7.6 [basic.align] paragraph 9 says,

If a request for a specific extended alignment in a specific context is not supported by an implementation, the implementation may reject the request as ill-formed. The implementation may also silently ignore the requested alignment.

In contrast, 9.12.2 [dcl.align] paragraph 2, bullet 4 says simply,

with no provision to “silently ignore” the requested alignment. These two passages need to be reconciled.

If the outcome of the reconciliation is to grant implementations the license to accept and ignore extended alignment requests, the specification should be framed in terms of mechanisms that already exist in the Standard, such as undefined behavior and/or conditionally-supported constructs; “ill-formed” is a category that is defined by the Standard, not something that an implementation can decide.

Notes from the February, 2008 meeting:

The consensus was that such requests should be ill-formed and require a diagnostic. However, it was also observed that an implementation need not reject an ill-formed program; the only requirement is that it issue a diagnostic. It would thus be permissible for an implementation to “noisily ignore” (as opposed to “silently ignoring”) an unsupported alignment request.

Proposed resolution (June, 2008):

Change 6.7.6 [basic.align] paragraph 9 as follows:

If a request for a specific extended alignment in a specific context is not supported by an implementation, the implementation may reject the request as program is ill-formed. The implementation may also silently ignore the requested alignment. [Note: aAdditionally, a request for runtime allocation of dynamic memory storage for which the requested alignment cannot be honored may shall be treated as an allocation failure. end note]



86. Lifetime of temporaries in query expressions

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Steve Adamczyk     Date: Jan 1999

[Voted into WP at April, 2006 meeting.]

In 6.7.7 [class.temporary] paragraph 5, should binding a reference to the result of a "?" operation, each of whose branches is a temporary, extend both temporaries?

Here's an example:

    const SFileName &C = noDir ? SFileName("abc") : SFileName("bcd");

Do the temporaries created by the SFileName conversions survive the end of the full expression?

Notes from 10/00 meeting:

Other problematic examples include cases where the temporary from one branch is a base class of the temporary from the other (i.e., where the implementation must remember which type of temporary must be destroyed), or where one branch is a temporary and the other is not. Similar questions also apply to the comma operator. The sense of the core language working group was that implementations should be required to support these kinds of code.

Notes from the March 2004 meeting:

We decided that the cleanest model is one in which any "?" operation that returns a class rvalue always copies one of its operands to a temporary and returns the temporary as the result of the operation. (Note that this may involve slicing.) An implementation would be free to optimize this using the rules in 11.4.5.3 [class.copy.ctor] paragraph 15, and in fact we would expect that in many cases compilers would do such optimizations. For example, the compiler could construct both rvalues in the above example into a single temporary, and thus avoid a copy.

See also issue 446.

Proposed resolution (October, 2004):

This issue is resolved by the resolutions of issue 446.

Note (October, 2005):

This issue was overlooked when issue 446 was moved to “ready” status and was thus inadvertently omitted from the list of issues accepted as Defect Reports at the October, 2005 meeting.




124. Lifetime of temporaries in default initialization of class arrays

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Jack Rouse     Date: 3 June 1999

[Moved to DR at 4/01 meeting.]

Jack Rouse: 6.7.7 [class.temporary] states that temporary objects will normally be destroyed at the end of the full expression in which they are created. This can create some unique code generation requirements when initializing a class array with a default constructor that uses a default argument. Consider the code:

    struct T {
       int i;
       T( int );
       ~T();
    };

    struct S {
       S( int = T(0).i );
       ~S();
    };

    S* f( int n )
    {
       return new S[n];
    }
The full expression allocating the array in f(int) includes the default constructor for S. Therefore according to 6.9.1 [intro.execution] paragraph 14, it includes the default argument expression for S(int). So evaluation of the full expression should include evaluating the default argument "n" times and creating "n" temporaries of type T. But the destruction of the temporaries must be delayed until the end of the full expression so this requires allocating space at runtime for "n" distinct temporaries. It is unclear how these temporaries are supposed to be allocated and deallocated. They cannot readily be autos because a variable allocation is required.

I believe that many existing implementations will destroy the temporaries needed by the default constructor after each array element is initialized. But I can't find anything in the standard that allows the temporaries to be destroyed early in this case.

I think the standard should allow the early destruction of temporaries used in the default initialization of class array elements. I believe early destruction is the status quo, and I don't think the users of existing C++ compilers have been adversely impacted by it.

Proposed resolution (04/01):

The proposed resolution is contained in the proposal for issue 201.




199. Order of destruction of temporaries

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Alan Nash     Date: 27 Jan 2000

[Voted into the WP at the April, 2007 meeting as part of paper J16/07-0099 = WG21 N2239.]

6.7.7 [class.temporary] paragraph 3 simply states the requirement that temporaries created during the evaluation of an expression

are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.
There is nothing said about the relative order in which these temporaries are destroyed.

Paragraph 5, dealing with temporaries bound to references, says

the temporaries created during the evaluation of the expression initializing the reference, except the temporary to which the reference is bound, are destroyed at the end of the full-expression in which they are created and in the reverse order of the completion of their construction.
Is this difference intentional? May temporaries in expressions other than those initializing references be deleted in non-LIFO order?

Notes from 04/00 meeting:

Steve Adamczyk expressed concern about constraining implementations that are capable of fine-grained parallelism -- they may be unable to determine the order of construction without adding undesirable overhead.

Proposed resolution (April, 2007):

As specified in paper J16/07-0099 = WG21 N2239.




201. Order of destruction of temporaries in initializers

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Alan Nash     Date: 31 Jan 2000

[Moved to DR at 4/01 meeting.]

According to 6.7.7 [class.temporary] paragraph 4, an expression appearing as the initializer in an object definition constitutes a context "in which temporaries are destroyed at a different point than the end of the full-expression." It goes on to say that the temporary containing the value of the expression persists until after the initialization is complete (see also issue 117). This seems to presume that the end of the full-expression is a point earlier than the completion of the initialization.

However, according to 6.9.1 [intro.execution] paragraphs 12-13, the full-expression in such cases is, in fact, the entire initialization. If this is the case, the behavior described for temporaries in an initializer expression is simply the normal behavior of temporaries in any expression, and treating it as an exception to the general rule is both incorrect and confusing.

Proposed resolution (04/01):

[Note: this proposal also addresses issue 124.]

  1. Add to the end of 6.9.1 [intro.execution] paragraph 12:

    If the initializer for an object or sub-object is a full-expression, the initialization of the object or sub-object (e.g., by calling a constructor or copying an expression value) is considered to be part of the full-expression.
  2. Replace 6.7.7 [class.temporary] paragraph 4 with:

    There are two 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. If the constructor has one or more default arguments, any temporaries created in the default argument expressions are destroyed immediately after return from the constructor.



320. Question on copy constructor elision example

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Steve Clamage     Date: 2 Nov 2001

[Voted into WP at April 2005 meeting.]

Section 6.7.7 [class.temporary] paragraph 2, abridged:

  X f(X);
  void g()
  {
	X a;
	a = f(a);
  }

a=f(a) requires a temporary for either the argument a or the result of f(a) to avoid undesired aliasing of a.

The note seems to imply that an implementation is allowed to omit copying "a" to f's formal argument, or to omit using a temporary for the return value of f. I don't find that license in normative text.

Function f returns an X by value, and in the expression the value is assigned (not copy-constructed) to "a". I don't see how that temporary can be omitted. (See also 11.4.5.3 [class.copy.ctor] p 15)

Since "a" is an lvalue and not a temporary, I don't see how copying "a" to f's formal parameter can be avoided.

Am I missing something, or is 6.7.7 [class.temporary] p 2 misleading?

Proposed resolution (October, 2004):

In 6.7.7 [class.temporary] paragraph 2, change the last sentence as indicated:

On the other hand, the expression a=f(a) requires a temporary for either the argument a or the result of f(a) to avoid undesired aliasing of a the result of f(a), which is then assigned to a.



392. Use of full expression lvalue before temporary destruction

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Stephen Clamage     Date: 21 Nov 2002

[Voted into WP at March 2004 meeting.]

class C {
public:
    C();
    ~C();
    int& get() { return p; } // reference return
private:
    int p;
};

int main ()
{
    if ( C().get() ) // OK?
}

Section 6.7.7 [class.temporary] paragraph 3 says a temp is destroyed as the last step in evaluating the full expression. But the expression C().get() has a reference type. Does 6.7.7 [class.temporary] paragraph 3 require that the dereference to get a boolean result occur before the destructor runs, making the code valid? Or does the code have undefined behavior?

Bill Gibbons: It has undefined behavior, though clearly this wasn't intended. The lvalue-to-rvalue conversion that occurs in the "if" statement is not currently part of the full-expression.

From section 6.7.7 [class.temporary] paragraph 3:

Temporary objects are destroyed as the last step in evaluating the full-expression (6.9.1 [intro.execution]) that (lexically) contains the point where they were created.

From section 6.9.1 [intro.execution] paragraph 12:

A full-expression is an expression that is not a subexpression of another expression. If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition.

The note in section 6.9.1 [intro.execution] paragraph 12 goes on to explain that this covers expressions used as initializers, but it does not discuss lvalues within temporaries.

It is a small point but it is probably worth correcting 6.9.1 [intro.execution] paragraph 12. Instead of the "implicit call of a function" wording, it might be better to just say that a full-expression includes any implicit use of the expression value in the enclosing language construct, and include a note giving implicit calls and lvalue-to-rvalue conversions as examples.

Offhand the places where this matters include: initialization (including member initializers), selection statements, iteration statements, return, throw

Proposed resolution (April 2003):

Change 6.9.1 [intro.execution] paragraph 12-13 to read:

A full-expression is an expression that is not a subexpression of another expression. If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression.

[Note: certain contexts in C++ cause the evaluation of a full-expression that results from a syntactic construct other than expression (7.6.20 [expr.comma]). For example, in 9.4 [dcl.init] one syntax for initializer is

but the resulting construct is a function call upon a constructor function with expression-list as an argument list; such a function call is a full-expression. For example, in 9.4 [dcl.init], another syntax for initializer is but again the resulting construct might be a function call upon a constructor function with one assignment-expression as an argument; again, the function call is a full-expression. ] [Example:

  struct S {
      S(int i): I(i) { }
      int& v() { return I; }
    private:
      int I;
  };

  S s1(1);           // full-expression is call of S::S(int)
  S s2 = 2;          // full-expression is call of S::S(int)

  void f() {
      if (S(3).v())  // full-expression includes lvalue-to-rvalue and
                     // int to bool conversions, performed before
                     // temporary is deleted at end of full-expression
      { }
  }

end example]



443. Wording nit in description of lifetime of temporaries

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Matthias Hofmann     Date: 2 Dec 2003

[Voted into WP at April 2005 meeting.]

There seems to be a typo in 6.7.7 [class.temporary]/5, which says "The temporary to which the reference is bound or the temporary that is the complete object TO a subobject OF which the TEMPORARY is bound persists for the lifetime of the reference except as specified below."

I think this should be "The temporary to which the reference is bound or the temporary that is the complete object OF a subobject TO which the REFERENCE is bound persists for the lifetime of the reference except as specified below."

I used upper-case letters for the parts I think need to be changed.

Proposed resolution (October, 2004):

Change 6.7.7 [class.temporary] paragraph 5 as indicated:

The temporary to which the reference is bound or the temporary that is the complete object to of a subobject of to which the temporary reference is bound persists for the lifetime of the reference except as specified below.



464. Wording nit on lifetime of temporaries to which references are bound

Section: 6.7.7  [class.temporary]     Status: CD1     Submitter: Allan Odgaard     Date: 21 Feb 2004

[Voted into WP at April, 2006 meeting.]

Section 6.7.7 [class.temporary] paragraph 5 ends with this "rule":

[...] if obj2 is an object with static or automatic storage duration created after the temporary is created, the temporary shall be destroyed after obj2 is destroyed.

For the temporary to be destroyed after obj2 is destroyed, when obj2 has static storage, I would say that the reference to the temporary should also have static storage, but that is IMHO not clear from the paragraph.

Example:

    void f ()
    {
       const T1& ref = T1();
       static T2 obj2;
       ...
    }

Here the temporary would be destoyed before obj2, contrary to the rule above.

Steve Adamczyk: I agree there's a minor issue here. I think the clause quoted above meant for obj1 and obj2 to have the same storage duration. Replacing "obj2 is an object with static or automatic storage duration" by "obj2 is an object with the same storage duration as obj1" would, I believe, fix the problem.

Notes from October 2004 meeting:

We agreed with Steve Adamczyk's suggestion.

Proposed resolution (October, 2005):

Change 6.7.7 [class.temporary] paragraph 5 as follows:

... In addition, the destruction of temporaries bound to references shall take into account the ordering of destruction of objects with static or automatic storage duration (6.7.5.2 [basic.stc.static], 6.7.5.4 [basic.stc.auto]); that is, if obj1 is an object with static or automatic storage duration created before the temporary is created with the same storage duration as the temporary, the temporary shall be destroyed before obj1 is destroyed; if obj2 is an object with static or automatic storage duration created after the temporary is created with the same storage duration as the temporary, the temporary shall be destroyed after obj2 is destroyed...



644. Should a trivial class type be a literal type?

Section: 6.8  [basic.types]     Status: CD1     Submitter: Alisdair Meredith     Date: 8 Aug 2007

[Voted into the WP at the June, 2008 meeting.]

The original proposed wording for 6.8 [basic.types] paragraph 11 required a constexpr constructor for a literal class only “if the class has at least one user-declared constructor.” This wording was dropped during the review by CWG out of a desire to ensure that literal types not have any uninitialized members. Thus, a class like

    struct pixel {
        int x, y;
    };

is not a literal type. However, if an object of that type is aggregate-initialized or value-initialized, there can be no uninitialized members; the missing wording should be restored in order to permit use of expressions like pixel().x as constant expressions.

Proposed resolution (February, 2008):

Change 6.8 [basic.types] paragraph 10 as follows:

A type is a literal type if it is:



637. Sequencing rules and example disagree

Section: 6.9.1  [intro.execution]     Status: CD1     Submitter: Ofer Porat     Date: 2 June 2007

[Voted into the WP at the September, 2008 meeting.]

In 6.9.1 [intro.execution] paragraph 16, the following expression is still listed as an example of undefined behavior:

    i = ++i + 1;

However, it appears that the new sequencing rules make this expression well-defined:

  1. The assignment side-effect is required to be sequenced after the value computations of both its LHS and RHS (7.6.19 [expr.ass] paragraph 1).

  2. The LHS (i) is an lvalue, so its value computation involves computing the address of i.

  3. In order to value-compute the RHS (++i + 1), it is necessary to first value-compute the lvalue expression ++i and then do an lvalue-to-rvalue conversion on the result. This guarantees that the incrementation side-effect is sequenced before the computation of the addition operation, which in turn is sequenced before the assignment side effect. In other words, it yields a well-defined order and final value for this expression.

It should be noted that a similar expression

    i = i++ + 1;

is still not well-defined, since the incrementation side-effect remains unsequenced with respect to the assignment side-effect.

It's unclear whether making the expression in the example well-defined was intentional or just a coincidental byproduct of the new sequencing rules. In either case either the example should be fixed, or the rules should be changed.

Clark Nelson: In my opinion, the poster's argument is perfectly correct. The rules adopted reflect the CWG's desired outcome for issue 222. At the Portland meeting, I presented (and still sympathize with) Tom Plum's case that these rules go a little too far in nailing down required behavior; this is a consequence of that.

One way or another, a change needs to be made, and I think we should seriously consider weakening the resolution of issue 222 to keep this example as having undefined behavior. This could be done fairly simply by having the sequencing requirements for an assignment expression depend on whether it appears in an lvalue context.

James Widman: How's this for a possible re-wording?

In all cases, the side effect of the assignment expression is sequenced after the value computations of the right and left operands. Furthermore, if the assignment expression appears in a context where an lvalue is required, the side effect of the assignment expression is sequenced before its value computation.

Notes from the February, 2008 meeting:

There was no real support in the CWG for weakening the resolution of issue 222 and returning the example to having undefined behavior. No one knew of an implementation that doesn't already do the (newly) right thing for such an example, so there was little motivation to go out of our way to increase the domain of undefined behavior. So the proposed resolution is to change the example to one that definitely does have undependable behavior in existing practice, and undefined behavior under the new rules.

Also, the new formulation of the sequencing rules approved in Oxford contained the wording that by and large resolved issue 222, so with the resolution of this issue, we can also close issue 222.

Proposed resolution (March, 2008):

Change the example in 6.9.1 [intro.execution] paragraph 16 as follows:

    i = v[i++];             // the behavior is undefined
    i = 7, i++, i++;        // i becomes 9
    i = ++i i++ + 1;        // the behavior is undefined
    i = i + 1;              // the value of i is incremented

This resolution also resolves issue 222.




639. What makes side effects “different” from one another?

Section: 6.9.1  [intro.execution]     Status: CD1     Submitter: James Widman     Date: 26 July 2007

[Voted into the WP at the September, 2008 meeting.]

Is the behavior undefined in the following example?

    void f() {
         int n = 0;
         n = --n;
    }

6.9.1 [intro.execution] paragraph 16 says,

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

It's not clear to me whether the two side-effects in n=--n are “different.” As far as I can tell, it seems that both side-effects involve the assignment of -1 to n, which in a sense makes them non-“different.” But I don't know if that's the intent. Would it be better to say “another” instead of “a different?”

On a related note, can we include this example to illustrate?

    void f( int, int );
    void g( int a ) { f( a = -1, a = -1 ); } // Undefined?

Proposed resolution (March, 2008):

Change 6.9.1 [intro.execution] paragraph 16 as follows:

...If a side effect on a scalar object is unsequenced relative to either a different another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. [Example:

    void f(int, int);
    void g(int i, int* v) {
        i = v[i++];         // the behavior is undefined
        i = 7, i++, i++;    // i becomes 9

        i = ++i + 1;        // the behavior is undefined
        i = i + 1;          // the value of i is incremented

        f(i = -1, i = -1);  // the behavior is undefined
    }

end example] When calling...




270. Order of initialization of static data members of class templates

Section: 6.9.3.2  [basic.start.static]     Status: CD1     Submitter: Jonathan H. Lundquist     Date: 9 Feb 2001

[Moved to DR at 4/02 meeting.]

The Standard does not appear to address how the rules for order of initialization apply to static data members of class templates.

Suggested resolution: Add the following verbiage to either 6.9.3.2 [basic.start.static] or 11.4.9.3 [class.static.data]:

Initialization of static data members of class templates shall be performed during the initialization of static data members for the first translation unit to have static initialization performed for which the template member has been instantiated. This requirement shall apply to both the static and dynamic phases of initialization.

Notes from 04/01 meeting:

Enforcing an order of initialization on static data members of class templates will result in substantial overhead on access to such variables. The problem is that the initialization be required as the result of instantiation in a function used in the initialization of a variable in another translation unit. In current systems, the order of initialization of static data data members of class templates is not predictable. The proposed resolution is to state that the order of initialization is undefined.

Proposed resolution (04/01, updated slightly 10/01):

Replace the following sentence in 6.9.3.2 [basic.start.static] paragraph 1:

Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.

with

Dynamic initialization of an object is either ordered or unordered. Explicit specializations and definitions of class template static data members have ordered initialization. Other class template static data member instances have unordered initialization. Other objects defined in namespace scope have ordered initialization. Objects defined within a single translation unit and with ordered initialization shall be initialized in the order of their definitions in the translation unit. The order of initialization is unspecified for objects with unordered initialization and for objects defined in different translation units.

Note that this wording is further updated by issue 362.

Note (07/01):

Brian McNamara argues against the proposed resolution. The following excerpt captures the central point of a long message on comp.std.c++:

I have a class for representing linked lists which looks something like
    template <class T>
    class List {
       ...  static List<T>* sentinel; ...
    };

    template <class T>
    List<T>* List<T>::sentinel( new List<T> ); // static member definition

The sentinel list node is used to represent "nil" (the null pointer cannot be used with my implementation, for reasons which are immaterial to this discussion). All of the List's non-static member functions and constructors depend upon the value of the sentinel. Under the proposed resolution for issue #270, Lists cannot be safely instantiated before main() begins, as the sentinel's initialization is "unordered".

(Some readers may propose that I should use the "singleton pattern" in the List class. This is undesirable, for reasons I shall describe at the end of this post at the location marked "[*]". For the moment, indulge me by assuming that "singleton" is not an adequate solution.)

Though this is a particular example from my own experience, I believe it is representative of a general class of examples. It is common to use static data members of a class to represent the "distinguished values" which are important to instances of that class. It is imperative that these values be initialized before any instances of the class are created, as the instances depend on the values.

In a comp.std.c++ posting on 28 Jul 2001, Brian McNamara proposes the following alternative resolution:

Replace the following sentence in 6.9.3.2 [basic.start.static] paragraph 1:

Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.
with
Objects with static storage duration defined in namespace scope shall be initialized in the order described below.
and then after paragraph 1, add this text:
Dynamic initialization is either ordered or quasi-ordered. Explicit specializations of class template static data members have ordered initialization. Other class template static data member instances have quasi-ordered initialization. All other objects defined in namespace scope have ordered initialization. The order of initialization is specified as follows:
along with a non-normative note along the lines of
[ Note: The intention is that translation units can each be compiled separately with no knowledge of what objects may be re-defined in other translation units. Each translation unit can contain a method which initializes all objects (both quasi-ordered and ordered) as though they were ordered. When these translation units are linked together to create an executable program, all of these objects can be initialized by simply calling the initialization methods (one from each translation unit) in any order. Quasi-ordered objects require some kind of guard to ensure that they are not initialized more than once (the first attempt to initialize such an object should succeed; any subsequent attempts should simply be ignored). ]

Erwin Unruh replies: There is a point which is not mentioned with this posting. It is the cost for implementing the scheme. It requires that each static template variable is instantiated in ALL translation units where it is used. There has to be a flag for each of these variables and this flag has to be checked in each TU where the instantiation took place.

I would reject this idea and stand with the proposed resolution of issue 270.

There just is no portable way to ensure the "right" ordering of construction.

Notes from 10/01 meeting:

The Core Working Group reaffirmed its previous decision.




441. Ordering of static reference initialization

Section: 6.9.3.2  [basic.start.static]     Status: CD1     Submitter: Mike Miller     Date: 1 Dec 2003

[Voted into WP at April 2005 meeting.]

I have a couple of questions about 6.9.3.2 [basic.start.static], "Initialization of non-local objects." I believe I recall some discussion of related topics, but I can't find anything relevant in the issues list.

The first question arose when I discovered that different implementations treat reference initialization differently. Consider, for example, the following (namespace-scope) code:

  int i;
  int& ir = i;
  int* ip = &i;
Both initializers, "i" and "&i", are constant expressions, per 7.7 [expr.const] paragraph 4-5 (a reference constant expression and an address constant expression, respectively). Thus, both initializations are categorized as static initialization, according to 6.9.3.2 [basic.start.static] paragraph 1:
Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization.

However, that does not mean that both ir and ip must be initialized at the same time:

Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place.

Because "int&" is not a POD type, there is no requirement that it be initialized before dynamic initialization is performed, and implementations differ in this regard. Using a function called during dynamic initialization to print the values of "ip" and "&ir", I found that g++, Sun, HP, and Intel compilers initialize ir before dynamic initialization and the Microsoft compiler does not. All initialize ip before dynamic initialization. I believe this is conforming (albeit inconvenient :-) behavior.

So, my first question is whether it is intentional that a reference of static duration, initialized with a reference constant expression, need not be initialized before dynamic initialization takes place, and if so, why?

The second question is somewhat broader. As 6.9.3.2 [basic.start.static] is currently worded, it appears that there are no requirements on when ir is initialized. In fact, there is a whole category of objects -- non-POD objects initialized with a constant expression -- for which no ordering is specified. Because they are categorized as part of "static initialization," they are not subject to the requirement that they "shall be initialized in the order in which their definition appears in the translation unit." Because they are not POD types, they are not required to be initialized before dynamic initialization occurs. Am I reading this right?

My preference would be to change 6.9.3.2 [basic.start.static] paragraph 1 so that 1) references are treated like POD objects with respect to initialization, and 2) "static initialization" applies only to POD objects and references. Here's some sample wording to illustrate:

Suggested resolution:

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Initializing a reference, or an object of POD type, of static storage duration with a constant expression (5.19) is called constant initialization. Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place. [Remainder unchanged.]

Proposed Resolution:

Change 6.9.3.2 [basic.start.static] paragraph 1 as follows:

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Initializing a reference, or an object of POD type, of static storage duration with a constant expression (5.19) is called constant initialization. Together, zero-initialization and constant initialization are Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place.



688. Constexpr constructors and static initialization

Section: 6.9.3.2  [basic.start.static]     Status: CD1     Submitter: Peter Dimov     Date: 26 March, 2008

[Voted into the WP at the September, 2008 meeting (resolution in paper N2757).]

Given this literal type,

    struct X {
        constexpr X() { }
    };

and this definition,

    static X x;

the current specification does not require that x be statically initialized because it is not “initialized with a constant expression” (6.9.3.1 [basic.start.main] paragraph 1) .

Lawrence Crowl:

This guarantee is essential for atomics.

Jens Maurer:

Suggestion:

A reference with static storage duration or an object of literal type with static storage duration can be initialized with a constant expression (7.7 [expr.const]) or with a constexpr constructor; this is called constant initialization.

(Not spelling out “default constructor” makes it easier to handle multiple-parameter constexpr constructors, where there isn't “a” constant expression but several.)

Peter Dimov:

In addition, there is a need to enforce static initialization for non-literal types: std::shared_ptr, std::once_flag, and std::atomic_* all have nontrivial copy constructors, making them non-literal types. However, we need a way to ensure that a constexpr constructor called with constant expressions will guarantee static initialization, regardless of the nontriviality of the copy constructor.

Proposed resolution (April, 2008):

  1. Change 6.9.3.2 [basic.start.static] paragraph 1 as follows:

  2. ...A reference with static storage duration and an object of trivial or literal type with static storage duration can be initialized with a constant expression (7.7 [expr.const]); this If a reference with static storage duration is initialized with a constant expression (7.7 [expr.const]) or if the initialization of an object with static storage duration satisfies the requirements for the object being declared with constexpr (9.2.6 [dcl.constexpr]), that initialization is called constant initialization...
  3. Change 8.8 [stmt.dcl] paragraph 4 as follows:

  4. ...A local object of trivial or literal type (6.8 [basic.types]) with static storage duration initialized with constant-expressions is initialized Constant initialization (6.9.3.2 [basic.start.static]) of a local entity with static storage duration is performed before its block is first entered...
  5. Change 9.2.6 [dcl.constexpr] paragraph 7 as follows:

  6. A constexpr specifier used in an object declaration declares the object as const. Such an object shall be initialized, and every expression that appears in its initializer (9.4 [dcl.init]) shall be a constant expression. Every implicit conversion used in converting the initializer expressions and every constructor call used for the initialization shall be one of those allowed in a constant expression (7.7 [expr.const])...
  7. Replace 9.4.2 [dcl.init.aggr] paragraph 14 as follows:

  8. When an aggregate with static storage duration is initialized with a brace-enclosed initializer-list, if all the member initializer expressions are constant expressions, and the aggregate is a trivial type, the initialization shall be done during the static phase of initialization (6.9.3.2 [basic.start.static]); otherwise, it is unspecified whether the initialization of members with constant expressions takes place during the static phase or during the dynamic phase of initialization. [Note: The order of initialization for aggregates with static storage duration is specified in 6.9.3.2 [basic.start.static] and 8.8 [stmt.dcl]. —end note]

(Note: the change to 6.9.3.2 [basic.start.static] paragraph 1 needs to be reconciled with the conflicting change in issue 684.)




28. 'exit', 'signal' and static object destruction

Section: 6.9.3.3  [basic.start.dynamic]     Status: CD1     Submitter: Martin J. O'Riordan     Date: 19 Oct 1997

[Voted into the WP at the June, 2008 meeting.]

The C++ standard has inherited the definition of the 'exit' function more or less unchanged from ISO C.

However, when the 'exit' function is called, objects of static extent which have been initialised, will be destructed if their types posses a destructor.

In addition, the C++ standard has inherited the definition of the 'signal' function and its handlers from ISO C, also pretty much unchanged.

The C standard says that the only standard library functions that may be called while a signal handler is executing, are the functions 'abort', 'signal' and 'exit'.

This introduces a bit of a nasty turn, as it is not at all unusual for the destruction of static objects to have fairly complex destruction semantics, often associated with resource release. These quite commonly involve apparently simple actions such as calling 'fclose' for a FILE handle.

Having observed some very strange behaviour in a program recently which in handling a SIGTERM signal, called the 'exit' function as indicated by the C standard.

But unknown to the programmer, a library static object performed some complicated resource deallocation activities, and the program crashed.

The C++ standard says nothing about the interaction between signals, exit and static objects. My observations, was that in effect, because the destructor called a standard library function other than 'abort', 'exit' or 'signal', while transitively in the execution context of the signal handler, it was in fact non-compliant, and the behaviour was undefined anyway.

This is I believe a plausible judgement, but given the prevalence of this common programming technique, it seems to me that we need to say something a lot more positive about this interaction.

Curiously enough, the C standard fails to say anything about the analogous interaction with functions registered with 'atexit' ;-)

Proposed Resolution (10/98):

The current Committee Draft of the next version of the ISO C standard specifies that the only standard library function that may be called while a signal handler is executing is 'abort'. This would solve the above problem.

[This issue should remain open until it has been decided that the next version of the C++ standard will use the next version of the C standard as the basis for the behavior of 'signal'.]

Notes (November, 2006):

C89 is slightly contradictory here: It allows any signal handler to terminate by calling abort, exit, longjmp, but (for asynchronous signals, i.e. not those produced by abort or raise) then makes calling any library function other than signal with the current signal undefined behavior (C89 7.7.1.1). For synchronous signals, C99 forbids calls to raise, but imposes no other restrictions. For asynchronous signals, C99 allows only calls to abort, _Exit, and signal with the current signal (C99 7.14.1.1). The current C++ WP refers to “plain old functions” and “conforming C programs” (17.13 [support.runtime] paragraph 6).

Proposed Resolution (November, 2006):

Change the footnote in 17.13 [support.runtime] paragraph 6 as follows:

In particular, a signal handler using exception handling is very likely to have problems. Also, invoking std::exit may cause destruction of objects, including those of the standard library implementation, which, in general, yields undefined behavior in a signal handler (see 6.9.1 [intro.execution]).



222. Sequence points and lvalue-returning operators

Section: Clause 7  [expr]     Status: CD1     Submitter: Andrew Koenig     Date: 20 Dec 1999

[Voted into the WP at the September, 2008 meeting.]

I believe that the committee has neglected to take into account one of the differences between C and C++ when defining sequence points. As an example, consider

    (a += b) += c;

where a, b, and c all have type int. I believe that this expression has undefined behavior, even though it is well-formed. It is not well-formed in C, because += returns an rvalue there. The reason for the undefined behavior is that it modifies the value of `a' twice between sequence points.

Expressions such as this one are sometimes genuinely useful. Of course, we could write this particular example as

    a += b; a += c;

but what about

    void scale(double* p, int n, double x, double y) {
        for (int i = 0; i < n; ++i) {
            (p[i] *= x) += y;
        }
    }

All of the potential rewrites involve multiply-evaluating p[i] or unobvious circumlocations like creating references to the array element.

One way to deal with this issue would be to include built-in operators in the rule that puts a sequence point between evaluating a function's arguments and evaluating the function itself. However, that might be overkill: I see no reason to require that in

    x[i++] = y;

the contents of `i' must be incremented before the assignment.

A less stringent alternative might be to say that when a built-in operator yields an lvalue, the implementation shall not subsequently change the value of that object as a consequence of that operator.

I find it hard to imagine an implementation that does not do this already. Am I wrong? Is there any implementation out there that does not `do the right thing' already for (a += b) += c?

7.6.19 [expr.ass] paragraph 1 says,

The result of the assignment operation is the value stored in the left operand after the assignment has taken place; the result is an lvalue.

What is the normative effect of the words "after the assignment has taken place"? I think that phrase ought to mean that in addition to whatever constraints the rules about sequence points might impose on the implementation, assignment operators on built-in types have the additional constraint that they must store the left-hand side's new value before returning a reference to that object as their result.

One could argue that as the C++ standard currently stands, the effect of x = y = 0; is undefined. The reason is that it both fetches and stores the value of y, and does not fetch the value of y in order to compute its new value.

I'm suggesting that the phrase "after the assignment has taken place" should be read as constraining the implementation to set y to 0 before yielding the value of y as the result of the subexpression y = 0.

Note that this suggestion is different from asking that there be a sequence point after evaluation of an assignment. In particular, I am not suggesting that an order constraint be imposed on any side effects other than the assignment itself.

Francis Glassborow:

My understanding is that for a single variable:

  1. Multiple read accesses without a write are OK
  2. A single read access followed by a single write (of a value dependant on the read, so that the read MUST happen first) is OK
  3. A write followed by an actual read is undefined behaviour
  4. Multiple writes have undefined behaviour

It is the 3) that is often ignored because in practice the compiler hardly ever codes for the read because it already has that value but in complicated evaluations with a shortage of registers, that is not always the case. Without getting too close to the hardware, I think we both know that a read too close to a write can be problematical on some hardware.

So, in x = y = 0;, the implementation must NOT fetch a value from y, instead it has to "know" what that value will be (easy because it has just computed that in order to know what it must, at some time, store in y). From this I deduce that computing the lvalue (to know where to store) and the rvalue to know what is stored are two entirely independent actions that can occur in any order commensurate with the overall requirements that both operands for an operator be evaluated before the operator is.

Erwin Unruh:

C distinguishes between the resulting value of an assignment and putting the value in store. So in C a compiler might implement the statement x=y=0; either as x=0;y=0; or as y=0;x=0; In C the statement (x += 5) += 7; is not allowed because the first += yields an rvalue which is not allowed as left operand to +=. So in C an assignment is not a sequence of write/read because the result is not really "read".

In C++ we decided to make the result of assignment an lvalue. In this case we do not have the option to specify the "value" of the result. That is just the variable itself (or its address in a different view). So in C++, strictly speaking, the statement x=y=0; must be implemented as y=0;x=y; which makes a big difference if y is declared volatile.

Furthermore, I think undefined behaviour should not be the result of a single mentioning of a variable within an expression. So the statement (x +=5) += 7; should NOT have undefined behaviour.

In my view the semantics could be:

  1. if the result of an assignment is used as an rvalue, its value is that of the variable after assignment. The actual store takes place before the next sequence point, but may be before the value is used. This is consistent with C usage.
  2. if the result of an assignment is used as an lvalue to store another value, then the new value will be stored in the variable before the next sequence point. It is unspecified whether the first assigned value is stored intermediately.
  3. if the result of an assignment is used as an lvalue to take an address, that address is given (it doesn't change). The actual store of the new value takes place before the next sequence point.

Jerry Schwarz:

My recollection is different from Erwin's. I am confident that the intention when we decided to make assignments lvalues was not to change the semantics of evaluation of assignments. The semantics was supposed to remain the same as C's.

Ervin seems to assume that because assignments are lvalues, an assignment's value must be determined by a read of the location. But that was definitely not our intention. As he notes this has a significant impact on the semantics of assignment to a volatile variable. If Erwin's interpretation were correct we would have no way to write a volatile variable without also reading it.

Lawrence Crowl:

For x=y=0, lvalue semantics implies an lvalue to rvalue conversion on the result of y=0, which in turn implies a read. If y is volatile, lvalue semantics implies both a read and a write on y.

The standard apparently doesn't state whether there is a value dependence of the lvalue result on the completion of the assignment. Such a statement in the standard would solve the non-volatile C compatibility issue, and would be consistent with a user-implemented operator=.

Another possible approach is to state that primitive assignment operators have two results, an lvalue and a corresponding "after-store" rvalue. The rvalue result would be used when an rvalue is required, while the lvalue result would be used when an lvalue is required. However, this semantics is unsupportable for user-defined assignment operators, or at least inconsistent with all implementations that I know of. I would not enjoy trying to write such two-faced semantics.

Erwin Unruh:

The intent was for assignments to behave the same as in C. Unfortunately the change of the result to lvalue did not keep that. An "lvalue of type int" has no "int" value! So there is a difference between intent and the standard's wording.

So we have one of several choices:

I think the last one has the least impact on existing programs, but it is an ugly solution.

Andrew Koenig:

Whatever we may have intended, I do not think that there is any clean way of making

    volatile int v;
    int i;

    i = v = 42;
have the same semantics in C++ as it does in C. Like it or not, the subexpression v = 42 has the type ``reference to volatile int,'' so if this statement has any meaning at all, the meaning must be to store 42 in v and then fetch the value of v to assign it to i.

Indeed, if v is volatile, I cannot imagine a conscientious programmer writing a statement such as this one. Instead, I would expect to see

    v = 42;
    i = v;
if the intent is to store 42 in v and then fetch the (possibly changed) value of v, or
    v = 42;
    i = 42;
if the intent is to store 42 in both v and i.

What I do want is to ensure that expressions such as ``i = v = 42'' have well-defined semantics, as well as expressions such as (i = v) = 42 or, more realistically, (i += v) += 42 .

I wonder if the following resolution is sufficient:

Append to 7.6.19 [expr.ass] paragraph 1:

There is a sequence point between assigning the new value to the left operand and yielding the result of the assignment expression.

I believe that this proposal achieves my desired effect of not constraining when j is incremented in x[j++] = y, because I don't think there is a constraint on the relative order of incrementing j and executing the assignment. However, I do think it allows expressions such as (i += v) += 42, although with different semantics from C if v is volatile.

Notes on 10/01 meeting:

There was agreement that adding a sequence point is probably the right solution.

Notes from the 4/02 meeting:

The working group reaffirmed the sequence-point solution, but we will look for any counter-examples where efficiency would be harmed.

For drafting, we note that ++x is defined in 7.6.2.3 [expr.pre.incr] as equivalent to x+=1 and is therefore affected by this change. x++ is not affected. Also, we should update any list of all sequence points.

Notes from October 2004 meeting:

Discussion centered around whether a sequence point “between assigning the new value to the left operand and yielding the result of the expression” would require completion of all side effects of the operand expressions before the value of the assignment expression was used in another expression. The consensus opinion was that it would, that this is the definition of a sequence point. Jason Merrill pointed out that adding a sequence point after the assignment is essentially the same as rewriting

    b += a

as

    b += a, b

Clark Nelson expressed a desire for something like a “weak” sequence point that would force the assignment to occur but that would leave the side effects of the operands unconstrained. In support of this position, he cited the following expression:

    j = (i = j++)

With the proposed addition of a full sequence point after the assignment to i, the net effect is no change to j. However, both g++ and MSVC++ behave differently: if the previous value of j is 5, the value of the expression is 5 but j gets the value 6.

Clark Nelson will investigate alternative approaches and report back to the working group.

Proposed resolution (March, 2008):

This issue is resolved by the adoption of the sequencing rules and the resolution of issue 637.




351. Sequence point error: unspecified or undefined?

Section: Clause 7  [expr]     Status: CD1     Submitter: Andrew Koenig     Date: 23 April 2002

[Voted into WP at March 2004 meeting.]

I have found what looks like a bug in Clause 7 [expr], paragraph 4:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined. Example:
        i = v[i++];                     // the behavior is unspecified
        i = 7, i++, i++;                // i becomes 9

        i = ++i + 1;                    // the behavior is unspecified
        i = i + 1;                      // the value of i is incremented
--end example]

So which is it, unspecified or undefined?

Notes from October 2002 meeting:

We should find out what C99 says and do the same thing.

Proposed resolution (April 2003):

Change the example in Clause 7 [expr], paragraph 4 from

[Example:
i = v[i++];                     //  the behavior is unspecified
i = 7, i++, i++;                //   i  becomes  9

i = ++i + 1;                    //  the behavior is unspecified
i = i + 1;                      //  the value of  i  is incremented
--- end example]

to (changing "unspecified" to "undefined" twice)

[Example:
i = v[i++];                     //  the behavior is undefined
i = 7, i++, i++;                //   i  becomes  9

i = ++i + 1;                    //  the behavior is undefined
i = i + 1;                      //  the value of  i  is incremented
--- end example]



451. Expressions with invalid results and ill-formedness

Section: Clause 7  [expr]     Status: CD1     Submitter: Gennaro Prota     Date: 19 Jan 2004

[Voted into WP at October 2005 meeting.]

Clause 7 [expr] par. 5 of the standard says:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression (5.19), in which case the program is ill-formed.

Well, we do know that except in some contexts (e.g. controlling expression of a #if, array bounds), a compiler is not required to evaluate constant-expressions in compile time, right?

Now, let us consider, the following simple snippet:

  if (a && 1/0)
      ...
with a, to fix our attention, being *not* a constant expression. The quote above seems to say that since 1/0 is a constant (sub-)expression, the program is ill-formed. So, is it the intent that such ill-formedness is diagnosable at run-time? Or is it the intent that the above gives undefined behavior (if 1/0 is evaluated) and is not ill-formed?

I think the intent is actually the latter, so I propose the following rewording of the quoted section:

If an expression is evaluated but its result is not mathematically defined or not in the range of representable values for its type the behavior is undefined, unless such an expression is a constant expression (5.19) that shall be evaluated during program translation, in which case the program is ill-formed.

Rationale (March, 2004):

We feel the standard is clear enough. The quoted sentence does begin "If during the evaluation of an expression, ..." so the rest of the sentence does not apply to an expression that is not evaluated.

Note (September, 2004):

Gennaro Prota feels that the CWG missed the point of his original comment: unless a constant expression appears in a context that requires a constant expression, an implementation is permitted to defer its evaluation to runtime. An evaluation that fails at runtime cannot affect the well-formedness of the program; only expressions that are evaluated at compile time can make a program ill-formed.

The status has been reset to “open” to allow further discussion.

Proposed resolution (October, 2004):

Change paragraph 5 of Clause 7 [expr] as indicated:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression appears where an integral constant expression is required (7.7 [expr.const]), in which case the program is ill-formed.



158. Aliasing and qualification conversions

Section: 7.2.1  [basic.lval]     Status: CD1     Submitter: Mike Stump     Date: 20 Aug 1999

[Moved to DR at 4/02 meeting.]

7.2.1 [basic.lval] paragraph 15 lists the types via which an lvalue can be used to access the stored value of an object; using an lvalue type that is not listed results in undefined behavior. It is permitted to add cv-qualification to the actual type of the object in this access, but only at the top level of the type ("a cv-qualified version of the dynamic type of the object").

However, 7.3.6 [conv.qual] paragraph 4 permits a "conversion [to] add cv-qualifiers at levels other than the first in multi-level pointers." The combination of these two rules allows creation of pointers that cannot be dereferenced without causing undefined behavior. For instance:

    int* jp;
    const int * const * p1 = &jp;
    *p1;    // undefined behavior!

The reason that *p1 results in undefined behavior is that the type of the lvalue is const int * const", which is not "a cv-qualified version of" int*.

Since the conversion is permitted, we must give it defined semantics, hence we need to fix the wording in 7.2.1 [basic.lval] to include all possible conversions of the type via 7.3.6 [conv.qual].

Proposed resolution (04/01):

Add a new bullet to 7.2.1 [basic.lval] paragraph 15, following "a cv-qualified version of the dynamic type of the object:"




519. Null pointer preservation in void* conversions

Section: 7.3.12  [conv.ptr]     Status: CD1     Submitter: comp.std.c++     Date: 19 May 2005

[Voted into WP at April, 2006 meeting.]

The C standard says in 6.3.2.3, paragraph 4:

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

C++ appears to be incompatible with the first sentence in only two areas:

    A *a = 0;
    void *v = a;

C++ (7.3.12 [conv.ptr] paragraph 2) says nothing about the value of v.

    void *v = 0;
    A *b = (A*)v; // aka static_cast<A*>(v)

C++ (7.6.1.9 [expr.static.cast] paragraph 10) says nothing about the value of b.

Suggested changes:

  1. Add the following sentence to 7.3.12 [conv.ptr] paragraph 2:

  2. The null pointer value is converted to the null pointer value of the destination type.
  3. Add the following sentence to 7.6.1.9 [expr.static.cast] paragraph 10:

  4. The null pointer value (7.3.12 [conv.ptr]) is converted to the null pointer value of the destination type.

Proposed resolution (October, 2005):

  1. Add the indicated words to 7.3.12 [conv.ptr] paragraph 2:

  2. An rvalue of type “pointer to cv T,” where T is an object type, can be converted to an rvalue of type “pointer to cv void”. The result of converting a “pointer to cv T” to a “pointer to cv void” points to the start of the storage location where the object of type T resides, as if the object is a most derived object (6.7.2 [intro.object]) of type T (that is, not a base class subobject). The null pointer value is converted to the null pointer value of the destination type.
  3. Add the indicated words to 7.6.1.9 [expr.static.cast] paragraph 11:

  4. An rvalue of type “pointer to cv1 void” can be converted to an rvalue of type “pointer to cv2 T,” where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. The null pointer value is converted to the null pointer value of the destination type. A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value...



654. Conversions to and from nullptr_t

Section: 7.3.12  [conv.ptr]     Status: CD1     Submitter: Jason Merrill     Date: 7 October 2007

[Voted into the WP at the June, 2008 meeting as paper N2656.]

In the interest of promoting use of nullptr instead of the integer literal 0 as the null pointer constant, the proposal accepted by the Committee does not provide for converting a zero-valued integral constant to type std::nullptr_t. However, this omission reduces the utility of the feature for use in the library for smart pointers. In particular, the addition of that conversion (along with a converting constructor accepting a std::nullptr_t) would allow smart pointers to be used just like ordinary pointers in expressions like:

    if (p == 0) { }
    if (0 == p) { }
    if (p != 0) { }
    if (0 != p) { }
    p = 0;

The existing use of the “unspecified bool type” idiom supports this usage, but being able to use std::nullptr_t instead would be simpler and more elegant.

Jason Merrill: I have another reason to support the conversion as well: it seems to me very odd for nullptr_t to be more restrictive than void*. Anything we can do with an arbitrary pointer, we ought to be able to do with nullptr_t as well. Specifically, since there is a standard conversion from literal 0 to void*, and there is a standard conversion from void* to bool, nullptr_t should support the same conversions.

This changes two of the example lines in the proposal as adopted:

    if (nullptr) ;      // error, no conversion to bool
    if (nullptr == 0) ; // error

become

    if (nullptr) ;      // evaluates to false
    if( nullptr == 0 ); // evaluates to true

And later,

    char* ch3 = expr ? nullptr : nullptr; // ch3 is the null pointer value
    char* ch4 = expr ? 0 : nullptr;       // ch4 is the null pointer value
    int n3 = expr ? nullptr : nullptr;    // error, nullptr_t can't be converted to int
    int n4 = expr ? 0 : nullptr;          // error, nullptr_t can't be converted to int

I would also allow reinterpret_cast from nullptr_t to integral type, with the same semantics as a reinterpret_cast from the null pointer value to integral type.

Basically, I would like nullptr_t to act like a void* which is constrained to always be (void*)0.




480. Is a base of a virtual base also virtual?

Section: 7.3.13  [conv.mem]     Status: CD1     Submitter: Mark Mitchell     Date: 18 Oct 2004

[Voted into WP at the October, 2006 meeting.]

When the Standard refers to a virtual base class, it should be understood to include base classes of virtual bases. However, the Standard doesn't actually say this anywhere, so when 7.3.13 [conv.mem] (for example) forbids casting to a derived class member pointer from a virtual base class member pointer, it could be read as meaning:

  struct B {};
  struct D : public B {};
  struct D2 : virtual public D {};

  int B::*p;
  int D::*q;

  void f() {
    static_cast<int D2::*>(p);  // permitted
    static_cast<int D2::*>(q);  // forbidden
  }

Proposed resolution (October, 2005):

  1. Change 7.3.13 [conv.mem] paragraph 2 as indicated:

  2. ...If B is an inaccessible (11.8 [class.access]), ambiguous (6.5.2 [class.member.lookup]) or virtual (11.7.2 [class.mi]) base class of D, or a base class of a virtual base class of D, a program that necessitates this conversion is ill-formed...
  3. Change 7.6.1.9 [expr.static.cast] paragraph 2 as indicated:

  4. ...and B is not neither a virtual base class of D nor a base class of a virtual base class of D...
  5. Change 7.6.1.9 [expr.static.cast] paragraph 9 as indicated:

  6. ...and B is not neither a virtual base class of D nor a base class of a virtual base class of D...



113. Visibility of called function

Section: 7.6.1.3  [expr.call]     Status: CD1     Submitter: Christophe de Dinechin     Date: 5 May 1999

[Moved to DR at 10/01 meeting.]

Christophe de Dinechin: In 7.6.1.3 [expr.call] , paragraph 2 reads:

If no declaration of the called function is visible from the scope of the call the program is ill-formed.
I think nothing there or in the previous paragraph indicates that this does not apply to calls through pointer or virtual calls.

Mike Miller: "The called function" is unfortunate phraseology; it makes it sound as if it's referring to the function actually called, as opposed to the identifier in the postfix expression. It's wrong with respect to Koenig lookup, too (the declaration need not be visible if it can be found in a class or namespace associated with one or more of the arguments).

In fact, this paragraph should be a note. There's a general rule that says you have to find an unambiguous declaration of any name that is used (6.5 [basic.lookup] paragraph 1) ; the only reason this paragraph is here is to contrast with C's implicit declaration of called functions.

Proposed resolution:

Change section 7.6.1.3 [expr.call] paragraph 2 from:
If no declaration of the called function is visible from the scope of the call the program is ill-formed.
to:
[Note: if a function or member function name is used, and name lookup (6.5 [basic.lookup]) does not find a declaration of that name, the program is ill-formed. No function is implicitly declared by such a call. ]

(See also issue 218.)




118. Calls via pointers to virtual member functions

Section: 7.6.1.3  [expr.call]     Status: CD1     Submitter: Martin O'Riordan     Date: 17 May 1999

[Voted into the WP at the June, 2008 meeting.]

Martin O'Riordan: Having gone through all the relevant references in the IS, it is not conclusive that a call via a pointer to a virtual member function is polymorphic at all, and could legitimately be interpreted as being static.

Consider 7.6.1.3 [expr.call] paragraph 1:

The function called in a member function call is normally selected according to the static type of the object expression ( 11.7 [class.derived] ), but if that function is virtual and is not specified using a qualified-id then the function actually called will be the final overrider (11.7.3 [class.virtual] ) of the selected function in the dynamic type of the object expression.
Here it is quite specific that you get the polymorphic call only if you use the unqualified syntax. But, the address of a member function is "always" taken using the qualified syntax, which by inference would indicate that call with a PMF is static and not polymorphic! Not what was intended.

Yet other references such as 7.6.4 [expr.mptr.oper] paragraph 4:

If the dynamic type of the object does not contain the member to which the pointer refers, the behavior is undefined.
indicate that the opposite may have been intended, by stating that it is the dynamic type and not the static type that matters. Also, 7.6.4 [expr.mptr.oper] paragraph 6:
If the result of .* or ->* is a function, then that result can be used only as the operand for the function call operator (). [Example:
        (ptr_to_obj->*ptr_to_mfct)(10);
calls the member function denoted by ptr_to_mfct for the object pointed to by ptr_to_obj. ]
which also implies that it is the object pointed to that determines both the validity of the expression (the static type of 'ptr_to_obj' may not have a compatible function) and the implicit (polymorphic) meaning. Note too, that this is stated in the non-normative example text.

Andy Sawyer: Assuming the resolution is what I've assumed it is for the last umpteen years (i.e. it does the polymorphic thing), then the follow on to that is "Should there also be a way of selecting the non-polymorphic behaviour"?

Mike Miller: It might be argued that the current wording of 7.6.1.3 [expr.call] paragraph 1 does give polymorphic behavior to simple calls via pointers to members. (There is no qualified-id in obj.*pmf, and the IS says that if the function is not specified using a qualified-id, the final overrider will be called.) However, it clearly says the wrong thing when the pointer-to-member itself is specified using a qualified-id (obj.*X::pmf).

Bill Gibbons: The phrase qualified-id in 7.6.1.3 [expr.call] paragraph 1 refers to the id-expression and not to the "pointer-to-member expression" earlier in the paragraph:

For a member function call, the postfix expression shall be an implicit (11.4.3 [class.mfct.non.static] , 11.4.9 [class.static] ) or explicit class member access (7.6.1.5 [expr.ref] ) whose id-expression is a function member name, or a pointer-to-member expression (7.6.4 [expr.mptr.oper] ) selecting a function member.

Mike Miller: To be clear, here's an example:

    struct S {
	virtual void f();
    };
    void (S::*pmf)();
    void g(S* sp) {
	sp->f();         // 1: polymorphic
	sp->S::f();      // 2: non-polymorphic
	(sp->S::f)();    // 3: non-polymorphic
	(sp->*pmf)();    // 4: polymorphic
	(sp->*&S::f)();  // 5: polymorphic
    }

Notes from October 2002 meeting:

This was moved back to open for lack of a champion. Martin O'Riordan is not expected to be attending meetings.

Proposed resolution (February, 2008):

  1. Change 7.6.1.3 [expr.call] paragraph 1 as follows:

    ... For a member function call, the postfix expression shall be an implicit (11.4.3 [class.mfct.non.static], 11.4.9 [class.static]) or explicit class member access (7.6.1.5 [expr.ref]) whose id-expression is a function member name, or a pointer-to-member expression (7.6.4 [expr.mptr.oper]) selecting a function member. The first expression in the postfix expression is then called the object expression, and; the call is as a member of the object pointed to or referred to by the object expression (7.6.1.5 [expr.ref], 7.6.4 [expr.mptr.oper]). In the case of an implicit class member access, the implied object is the one pointed to by this. [Note: a member function call of the form f() is interpreted as (*this).f() (see 11.4.3 [class.mfct.non.static]). —end note] If a function or member function name is used, the name can be overloaded ( Clause 12 [over]), in which case the appropriate function shall be selected according to the rules in 12.2 [over.match]. The function called in a member function call is normally selected according to the static type of the object expression (11.7 [class.derived]), but if that function is virtual and is not specified using a qualified-id then the function actually called will be the final overrider (11.7.3 [class.virtual]) of the selected function in the dynamic type of the object expression If the selected function is non-virtual, or if the id-expression in the class member access expression is a qualified-id, that function is called. Otherwise, its final overrider (11.7.3 [class.virtual]) in the dynamic type of the object expression is called. ...
  2. Change 7.6.4 [expr.mptr.oper] paragraph 4 as follows:

    The first operand is called the object expression. If the dynamic type of the object expression does not contain the member to which the pointer refers, the behavior is undefined.



506. Conditionally-supported behavior for non-POD objects passed to ellipsis

Section: 7.6.1.3  [expr.call]     Status: CD1     Submitter: Mike Miller     Date: 14 Apr 2005

[Voted into WP at the October, 2006 meeting.]

The current wording of 7.6.1.3 [expr.call] paragraph 7 states:

When there is no parameter for a given argument, the argument is passed in such a way that the receiving function can obtain the value of the argument by invoking va_arg (17.13 [support.runtime]). The lvalue-to-rvalue (7.3.2 [conv.lval]), array-to-pointer (7.3.3 [conv.array]), and function-to-pointer (7.3.4 [conv.func]) standard conversions are performed on the argument expression. After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the program is ill-formed. If the argument has a non-POD class type ( Clause 11 [class]), the behavior is undefined.

Paper J16/04-0167=WG21 N1727 suggests that passing a non-POD object to ellipsis be ill-formed. In discussions at the Lillehammer meeting, however, the CWG felt that the newly-approved category of conditionally-supported behavior would be more appropriate.

Proposed resolution (October, 2005):

Change 7.6.1.3 [expr.call] paragraph 7 as indicated:

...After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the program is ill-formed. If the argument has a non-POD class type (clause 9), the behavior is undefined. Passing an argument of non-POD class type (clause 9) with no corresponding parameter is conditionally-supported, with implementation-defined semantics.



634. Conditionally-supported behavior for non-POD objects passed to ellipsis redux

Section: 7.6.1.3  [expr.call]     Status: CD1     Submitter: Howard Hinnant     Date: 6 Jun 2007

[Voted into the WP at the September, 2008 meeting.]

Issue 506 changed passing a non-POD class type to an ellipsis from undefined behavior to conditionally-supported behavior. As a result, an implementation could conceivably reject code like the following:

    struct two {char _[2];};

    template <class From, class To>
    struct is_convertible
    {
    private:
            static From f;

            template <class U> static char test(const U&);
            template <class U> static two test(...);
    public:
            static const bool value = sizeof(test<To>(f)) == 1;
    };

    struct A
    {
         A();
    };

    int main()
    {
         const bool b = is_convertible<A,int>::value;  // b == false
    }

This technique has become popular in template metaprogramming, and no non-POD object is actually passed at runtime. Concepts will eliminate much (perhaps not all) of the need for this kind of programming, but legacy code will persist.

Perhaps this technique should be officially supported by allowing implementations to reject passing a non-POD type to ellipsis only if it appears in a potentially-evaluated expression?

Notes from the July, 2007 meeting:

The CWG agreed with the suggestion to allow such calls in unevaluated contexts.

Proposed resolution (September, 2007):

Change 7.6.1.3 [expr.call] paragraph 7 as follows:

...Passing an a potentially-evaluated argument of non-trivial class type (Clause 11 [class]) with no corresponding parameter is conditionally-supported, with implementation-defined semantics...



421. Is rvalue.field an rvalue?

Section: 7.6.1.5  [expr.ref]     Status: CD1     Submitter: Gabriel Dos Reis     Date: 15 June 2003

[Voted into WP at March 2004 meeting.]

Consider

  typedef
    struct {
      int a;
    } A;

  A f(void)
  {
    A a;
    return a;
  }

  int main(void)
  {
    int* p = &f().a;   // #1
  }

Should #1 be rejected? The standard is currently silent.

Mike Miller: I don't believe the Standard is silent on this. I will agree that the wording of 7.6.1.5 [expr.ref] bullet 4.2 is unfortunate, as it is subject to misinterpretation. It reads,

If E1 is an lvalue, then E1.E2 is an lvalue.
The intent is, "and not otherwise."

Notes from October 2003 meeting:

We agree the reference should be an rvalue, and a change along the lines of that recommended by Mike Miller is reasonable.

Proposed Resolution (October 2003):

Change the second bullet of 7.6.1.5 [expr.ref] paragraph 4 to read:

If E1 is an lvalue, then E1.E2 is an lvalue; otherwise, it is an rvalue.



492. typeid constness inconsistent with example

Section: 7.6.1.8  [expr.typeid]     Status: CD1     Submitter: Ron Natalie     Date: 15 Dec 2004

[Voted into WP at April, 2006 meeting.]

There is an inconsistency between the normative text in section 7.6.1.8 [expr.typeid] and the example that follows.

Here is the relevant passage (starting with paragraph 4):

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of the type-id. If the type of the type-id is a reference type, the result of the typeid expression refers to a std::type_info object representing the referenced type.

The top-level cv-qualifiers of the lvalue expression or the type-id that is the operand of typeid are always ignored.

and the example:

    typeid(D) == typeid(const D&); // yields true

The second paragraph above says the “type-id that is the operand”. This would be const D&. In this case, the const is not at the top-level (i.e., applied to the operand itself).

By a strict reading, the above should yield false.

My proposal is that the strict reading of the normative test is correct. The example is wrong. Different compilers here give different answers.

Proposed resolution (April, 2005):

Change the second sentence of 7.6.1.8 [expr.typeid] paragraph 4 as follows:

If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified referenced type.



54. Static_cast from private base to derived class

Section: 7.6.1.9  [expr.static.cast]     Status: CD1     Submitter: Steve Adamczyk     Date: 13 Oct 1998

[Voted into WP at October 2004 meeting.]

Is it okay to use a static_cast to cast from a private base class to a derived class? That depends on what the words "valid standard conversion" in paragraph 8 mean — do they mean the conversion exists, or that it would not get an error if it were done? I think the former was intended — and therefore a static_cast from a private base to a derived class would be allowed.

Rationale (04/99): A static_cast from a private base to a derived class is not allowed outside a member from the derived class, because 7.3.12 [conv.ptr] paragraph 3 implies that the conversion is not valid. (Classic style casts work.)

Reopened September 2003:

Steve Adamczyk: It makes some sense to disallow the inverse conversion that is pointer-to-member of derived to pointer-to-member of private base. There's less justification for the pointer-to-private-base to pointer-to-derived case. EDG, g++ 3.2, and MSVC++ 7.1 allow the pointer case and disallow the pointer-to-member case. Sun disallows the pointer case as well.

  struct B {};
  struct D : private B {};
  int main() {
    B *p = 0;
    static_cast<D *>(p);  // Pointer case: should be allowed
    int D::*pm = 0;
    static_cast<int B::*>(pm);  // Pointer-to-member case: should get error
  }

There's a tricky case with old-style casts: because the static_cast interpretation is tried first, you want a case like the above to be considered a static_cast, but then issue an error, not be rejected as not a static cast; if you did the latter, you would then try the cast as a reinterpret_cast.

Ambiguity and casting to a virtual base should likewise be errors after the static_cast interpretation is selected.

Notes from the October 2003 meeting:

There was lots of sentiment for making things symmetrical: the pointer case should be the same as the pointer-to-member case. g++ 3.3 now issues errors on both cases.

We decided an error should be issued on both cases. The access part of the check should be done later; by some definition of the word the static_cast is valid, and then later an access error is issued. This is similar to the way standard conversions work.

Proposed Resolution (October 2003):

Replace paragraph 7.6.1.9 [expr.static.cast]/6:

The inverse of any standard conversion sequence ( 7.3 [conv]), other than the lvalue-to-rvalue (7.3.2 [conv.lval]), array-to-pointer (7.3.3 [conv.array]), function-to-pointer (7.3.4 [conv.func]), and boolean (7.3.14 [conv.fctptr]) conversions, can be performed explicitly using static_cast. The lvalue-to-rvalue (7.3.2 [conv.lval]), array-to-pointer (7.3.3 [conv.array]), and function-to-pointer (7.3.4 [conv.func]) conversions are applied to the operand. Such a static_cast is subject to the restriction that the explicit conversion does not cast away constness (7.6.1.11 [expr.const.cast]), and the following additional rules for specific cases:

with two paragraphs:

The inverse of any standard conversion sequence ( 7.3 [conv]), other than the lvalue-to-rvalue (7.3.2 [conv.lval]), array-to-pointer (7.3.3 [conv.array]), function-to-pointer (7.3.4 [conv.func]), and boolean (7.3.14 [conv.fctptr]) conversions, can be performed explicitly using static_cast. A program is ill-formed if it uses static_cast to perform the inverse of an ill-formed standard conversion sequence.[Example:

struct B {};
struct D : private B {};
void f() {
  static_cast<D*>((B*)0); // Error: B is a private base of D.
  static_cast<int B::*>((int D::*)0); // Error: B is a private base of D.
}
--- end example]

The lvalue-to-rvalue (7.3.2 [conv.lval]), array-to-pointer (7.3.3 [conv.array]), and function-to-pointer (7.3.4 [conv.func]) conversions are applied to the operand. Such a static_cast is subject to the restriction that the explicit conversion does not cast away constness (7.6.1.11 [expr.const.cast]), and the following additional rules for specific cases:

In addition, modify the second sentence of 7.6.3 [expr.cast]/5. The first two sentences of 7.6.3 [expr.cast]/5 presently read:

The conversions performed by can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply.

Change the second sentence to read:

The same semantic restrictions and behaviors apply, with the exception that in performing a static_cast in the following situations the conversion is valid even if the base class is inaccessible:

Remove paragraph 7.6.3 [expr.cast]/7, which presently reads:

In addition to those conversions, the following static_cast and reinterpret_cast operations (optionally followed by a const_cast operation) may be performed using the cast notation of explicit type conversion, even if the base class type is not accessible:



427. static_cast ambiguity: conversion versus cast to derived

Section: 7.6.1.9  [expr.static.cast]     Status: CD1     Submitter: Mark Mitchell     Date: 5 July 2003

[Voted into WP at October 2004 meeting.]

Consider this code:

  struct B {};

  struct D : public B {
    D(const B&);
  };

  extern B& b;

  void f() {
    static_cast<const D&>(b);
  }

The rules for static_cast permit the conversion to "const D&" in two ways:

  1. D is derived from B, and b is an lvalue, so a cast to D& is OK.
  2. const D& t = b is valid, using the constructor for D. [Ed. note: actually, this should be parenthesized initialization.]

The first alternative is 7.6.1.9 [expr.static.cast]/5; the second is 7.6.1.9 [expr.static.cast]/2.

Presumably the first alternative is better -- it's the "simpler" conversion. The standard does not seem to make that clear.

Steve Adamczyk: I take the "Otherwise" at the beginning of 7.6.1.9 [expr.static.cast]/3 as meaning that the paragraph 2 interpretation is used if available, which means in your example above interpretation 2 would be used. However, that's not what EDG's compiler does, and I agree that it's not the "simpler" conversion.

Proposed Resolution (October 2003):

Move paragraph 5.2.9/5:

An lvalue of type ``cv1 B'', where B is a class type, can be cast to type ``reference to cv2 D'', where D is a class derived ( 11.7 [class.derived]) from B, if a valid standard conversion from ``pointer to D'' to ``pointer to B'' exists (7.3.12 [conv.ptr]), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The result is an lvalue of type ``cv2 D.'' If the lvalue of type ``cv1 B'' is actually a sub-object of an object of type D, the lvalue refers to the enclosing object of type D. Otherwise, the result of the cast is undefined. [Example:

  struct B {};
  struct D : public B {};
  D d;
  B &br = d;

  static_cast<D&>(br);            //  produces lvalue to the original  d  object
--- end example]

before paragraph 7.6.1.9 [expr.static.cast]/2.

Insert Otherwise, before the text of paragraph 7.6.1.9 [expr.static.cast]/2 (which will become 7.6.1.9 [expr.static.cast]/3 after the above insertion), so that it reads:

Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration "T t(e);" is well-formed, for some invented temporary variable t (9.4 [dcl.init]). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The result is an lvalue if T is a reference type (9.3.4.3 [dcl.ref]), and an rvalue otherwise. The expression e is used as an lvalue if and only if the initialization uses it as an lvalue.




439. Guarantees on casting pointer back to cv-qualified version of original type

Section: 7.6.1.9  [expr.static.cast]     Status: CD1     Submitter: Mark Mitchell     Date: 30 Oct 2003

[Voted into WP at April 2005 meeting.]

Paragraph 7.6.1.9 [expr.static.cast] paragraph 10 says that:

A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type will have its original value.

That guarantee should be stronger. In particular, given:

  T* p1 = new T;
  const T* p2 = static_cast<const T*>(static_cast<void *>(p1));
  if (p1 != p2)
    abort ();
there should be no call to "abort". The last sentence of Paragraph 7.6.1.9 [expr.static.cast] paragraph 10 should be changed to read:

A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type (or a variant of the original pointer type that differs only in the cv-qualifiers applied to the object type) will have its original value. [Example:
T* p1 = new T;
const T* p2 = static_cast<const T*>(static_cast<void *>(p1));
bool b = p1 == p2; // b will have the value true.
---end example.]

Proposed resolution:

Change 7.6.1.9 [expr.static.cast] paragraph 10 as indicated:

A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type, possibly with different cv-qualification, will have its original value. [Example:

  T* p1 = new T;
  const T* p2 = static_cast<const T*>(static_cast<void *>(p1));
  bool b = p1 == p2; // b will have the value true.

---end example]

Rationale: The wording "possibly with different cv-qualification" was chosen over the suggested wording to allow for changes in cv-qualification at different levels in a multi-level pointer, rather than only at the object type level.




671. Explicit conversion from a scoped enumeration type to integral type

Section: 7.6.1.9  [expr.static.cast]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 22 December 2007

[Voted into the WP at the September, 2008 meeting.]

There appears to be no provision in the Standard for explicit conversion of a value of a scoped enumeration type to an integral type, even though the inverse conversion is permitted. That is,

    enum class E { e };
    static_cast<E>(0);       // #1: OK
    static_cast<int>(E::e);  // #2: error

This is because values of scope enumeration types (intentionally) cannot be implicitly converted to integral types (7.3.7 [conv.prom] and 7.3.9 [conv.integral]) and 7.6.1.9 [expr.static.cast] was not updated to permit #2, although #1 is covered by paragraph 8.

Proposed resolution (June, 2008):

Add the following as a new paragraph following 7.6.1.9 [expr.static.cast] paragraph 8:

A value of a scoped enumeration type (9.7.1 [dcl.enum]) can be explicitly converted to an integral type. The value is unchanged if the original value can be represented by the specified type. Otherwise, the resulting value is unspecified.



195. Converting between function and object pointers

Section: 7.6.1.10  [expr.reinterpret.cast]     Status: CD1     Submitter: Steve Clamage     Date: 12 Jan 2000

[Voted into WP at April 2005 meeting.]

It is currently not permitted to cast directly between a pointer to function type and a pointer to object type. This conversion is not listed in 7.6.1.9 [expr.static.cast] and 7.6.1.10 [expr.reinterpret.cast] and thus requires a diagnostic to be issued. However, if a sufficiently long integral type exists (as is the case in many implementations), it is permitted to cast between pointer to function types and pointer to object types using that integral type as an intermediary.

In C the cast results in undefined behavior and thus does not require a diagnostic, and Unix C compilers generally do not issue one. This fact is used in the definition of the standard Unix function dlsym, which is declared to return void* but in fact may return either a pointer to a function or a pointer to an object. The fact that C++ compilers are required to issue a diagnostic is viewed as a "competitive disadvantage" for the language.

Suggested resolution: Add wording to 7.6.1.10 [expr.reinterpret.cast] allowing conversions between pointer to function and pointer to object types, if the implementation has an integral data type that can be used as an intermediary.

Several points were raised in opposition to this suggestion:


  1. Early C++ supported this conversion and it was deliberately removed during the standardization process.
  2. The existence of an appropriate integral type is irrelevant to whether the conversion is "safe." The condition should be on whether information is lost in the conversion or not.
  3. There are numerous ways to address the problem at an implementation level rather than changing the language. For example, the compiler could recognize the specific case of dlsym and omit the diagnostic, or the C++ binding to dlsym could be changed (using templates, for instance) to circumvent the violation.
  4. The conversion is, in fact, not supported by C; the dlsym function is simply relying on non-mandated characteristics of C implementations, and we would be going beyond the requirements of C compatibility in requiring (some) implementations to support the conversion.
  5. This issue is in fact not a defect (omitted or self-contradictory requirements) in the current Standard; the proposed change would actually be an extension and should not be considered until the full review of the IS.
  6. dlsym appears not to be used very widely, and the declaration in the header file is not problematic, only calls to it. Since C code generally requires some porting to be valid C++ anyway, this should be considered one of those items that requires porting.

Martin O'Riordan suggested an alternative approach:


The advantage of this approach is that it would permit writing portable, well-defined programs involving such conversions. However, it breaks the current degree of compatibility between old and new casts, and it adds functionality to dynamic_cast which is not obviously related to its current meaning.

Notes from 04/00 meeting:

Andrew Koenig suggested yet another approach: specify that "no diagnostic is required" if the implementation supports the conversion.

Later note:

It was observed that conversion between function and data pointers is listed as a "common extension" in C99.

Notes on the 10/01 meeting:

It was decided that we want the conversion defined in such a way that it always exists but is always undefined (as opposed to existing only when the size relationship is appropriate, and being implementation-defined in that case). This would allow an implementation to issue an error at compile time if the conversion does not make sense.

Bill Gibbons notes that the definitions of the other similar casts are inconsistent in this regard. Perhaps they should be updated as well.

Proposed resolution (April 2003):

After 7.6.1.10 [expr.reinterpret.cast] paragraph 6, insert:

A pointer to a function can be explicitly converted to a pointer to a function of a different type. The effect of calling a function through a pointer to a function type (9.3.4.6 [dcl.fct]) that is not the same as the type used in the definition of the function is undefined. Except that converting an rvalue of type ``pointer to T1'' to the type ``pointer to T2'' (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified. [Note: see also 7.3.12 [conv.ptr] for more details of pointer conversions. ] It is implementation defined whether a conversion from pointer to object to pointer to function and/or a conversion from pointer to function to pointer to object exist.
and in paragraph 10:
An lvalue expression of type T1 can be cast to the type ``reference to T2'' if T1 and T2 are object types and an expression of type ``pointer to T1'' can be explicitly converted to the type ``pointer to T2'' using a reinterpret_cast. That is, a reference cast reinterpret_cast< T& >(x) has the same effect as the conversion *reinterpret_cast< T* >(&x) with the built-in & and * operators. The result is an lvalue that refers to the same object as the source lvalue, but with a different type. No temporary is created, no copy is made, and constructors (11.4.5 [class.ctor]) or conversion functions (11.4.8 [class.conv]) are not called.

Drafting Note:

If either conversion exists, the implementation already has to define the behavior (paragraph 3).

Notes from April 2003 meeting:

The new consensus is that if the implementation allows this cast, pointer-to-function converted to pointer-to-object converted back to the original pointer-to-function should work; anything else is undefined behavior. If the implementation does not allow the cast, it should be ill-formed.

Tom Plum is investigating a new concept, that of a "conditionally-defined" feature, which may be applicable here.

Proposed Resolution (October, 2004):

(See paper J16/04-0067 = WG21 N1627 for background material and rationale for this resolution. The resolution proposed here differs only editorially from the one in the paper.)

  1. Insert the following into Clause 3 [intro.defs] and renumber all following definitions accordingly:

    1.3.2  conditionally-supported behavior

    behavior evoked by a program construct that is not a mandatory requirement of this International Standard. If a given implementation supports the construct, the behavior shall be as described herein; otherwise, the implementation shall document that the construct is not supported and shall treat a program containing an occurrence of the construct as ill-formed (Clause 3 [intro.defs]).

  2. Add the indicated words to 4.1 [intro.compliance] paragraph 2, bullet 2:

  3. Insert the following as a new paragraph following 7.6.1.10 [expr.reinterpret.cast] paragraph 7:

    Converting a pointer to a function to a pointer to an object type or vice versa evokes conditionally-supported behavior. In any such conversion supported by an implementation, converting from an rvalue of one type to the other and back (possibly with different cv-qualification) shall yield the original pointer value; mappings between pointers to functions and pointers to objects are otherwise implementation-defined.
  4. Change 9.10 [dcl.asm] paragraph 1 as indicated:

    The meaning of an An asm declaration evokes conditionally-supported behavior. If supported, its meaning is implementation-defined.
  5. Change 9.11 [dcl.link] paragraph 2 as indicated:

    The string-literal indicates the required language linkage. The meaning of the string-literal is implementation-defined. A linkage-specification with a string that is unknown to the implementation is ill-formed. This International Standard specifies the semantics of C and C++ language linkage. Other values of the string-literal evoke conditionally-supported behavior, with implementation-defined semantics. [Note: Therefore, a linkage-specification with a string-literal that is unknown to the implementation requires a diagnostic. When the string-literal in a linkage-specification names a programming language, the spelling of the programming language's name is implementation-defined. [Note: It is recommended that the spelling be taken from the document defining that language, for example Ada (not ADA) and Fortran or FORTRAN (depending on the vintage). The semantics of a language linkage other than C++ or C are implementation-defined. ]
  6. Change Clause 13 [temp] paragraph 4 as indicated:

    A template, a template explicit specialization (13.9.4 [temp.expl.spec]), or a class template partial specialization shall not have C linkage. If the linkage of one of these is something other than C or C++, the behavior is implementation-defined result is conditionally-supported behavior, with implementation-defined semantics.



463. reinterpret_cast<T*>(0)

Section: 7.6.1.10  [expr.reinterpret.cast]     Status: CD1     Submitter: Gennaro Prota     Date: 14 Feb 2004

[Voted into WP at April, 2006 meeting.]

Is reinterpret_cast<T*>(null_pointer_constant) guaranteed to yield the null pointer value of type T*?

I think a committee clarification is needed. Here's why: 7.6.1.10 [expr.reinterpret.cast] par. 8 talks of "null pointer value", not "null pointer constant", so it would seem that

  reinterpret_cast<T*>(0)
is a normal int->T* conversion, with an implementation-defined result.

However a little note to 7.6.1.10 [expr.reinterpret.cast] par. 5 says:

Converting an integral constant expression (5.19) with value zero always yields a null pointer (4.10), but converting other expressions that happen to have value zero need not yield a null pointer.
Where is this supported in normative text? It seems that either the footnote or paragraph 8 doesn't reflect the intent.

SUGGESTED RESOLUTION: I think it would be better to drop the footnote #64 (and thus the special case for ICEs), for two reasons:

a) it's not normative anyway; so I doubt anyone is relying on the guarantee it hints at, unless that guarantee is given elsewhere in a normative part

b) users expect reinterpret_casts to be almost always implementation dependent, so this special case is a surprise. After all, if one wants a null pointer there's static_cast. And if one wants reinterpret_cast semantics the special case requires doing some explicit cheat, such as using a non-const variable as intermediary:

   int v = 0;
   reinterpret_cast<T*>(v); // implementation defined

   reinterpret_cast<T*>(0); // null pointer value of type T*
   const int w = 0;
   reinterpret_cast<T*>(w); // null pointer value of type T*

It seems that not only that's providing a duplicate functionality, but also at the cost to hide what seems the more natural one.

Notes from October 2004 meeting:

This footnote was added in 1996, after the invention of reinterpret_cast, so the presumption must be that it was intentional. At this time, however, the CWG feels that there is no reason to require that reinterpret_cast<T*>(0) produce a null pointer value as its result.

Proposed resolution (April, 2005):

  1. Delete the footnote in 7.6.1.10 [expr.reinterpret.cast] paragraph 5 reading,

    Converting an integral constant expression (7.7 [expr.const]) with value zero always yields a null pointer (7.3.12 [conv.ptr]), but converting other expressions that happen to have value zero need not yield a null pointer.
  2. Add the indicated note to 7.6.1.10 [expr.reinterpret.cast] paragraph 8:

    The null pointer value (7.3.12 [conv.ptr]) is converted to the null pointer value of the destination type. [Note: A null pointer constant, which has integral type, is not necessarily converted to a null pointer value. —end note]



324. Can "&" be applied to assignment to bit-field?

Section: 7.6.2.2  [expr.unary.op]     Status: CD1     Submitter: Alasdair Grant     Date: 27 Nov 2001

[Voted into WP at October 2003 meeting.]

An assignment returns an lvalue for its left operand. If that operand refers to a bit field, can the "&" operator be applied to the assignment? Can a reference be bound to it?

  struct S { int a:3; int b:3; int c:3; };

  void f()
  {
    struct S s;
    const int *p = &(s.b = 0);     // (a)
    const int &r = (s.b = 0);      // (b)
          int &r2 = (s.b = 0);     // (c)
  }

Notes from the 4/02 meeting:

The working group agreed that this should be an error.

Proposed resolution (October 2002):

In 7.6.2.3 [expr.pre.incr] paragraph 1 (prefix "++" and "--" operators), change

The value is the new value of the operand; it is an lvalue.
to
The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field.

In 7.6.16 [expr.cond] paragraph 4 ("?" operator), add the indicated text:

If the second and third operands are lvalues and have the same type, the result is of that type and is an lvalue and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields.

In 7.6.19 [expr.ass] paragraph 1 (assignment operators) add the indicated text (the original text is as updated by issue 221, which is DR but not in TC1):

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue with the type and value of the left operand after the assignment has taken place. The result in all cases is a bit-field if the left operand is a bit-field.

Note that issue 222 adds (non-conflicting) text at the end of this same paragraph (7.6.19 [expr.ass] paragraph 1).

In 7.6.20 [expr.comma] paragraph 1 (comma operator), change:

The type and value of the result are the type and value of the right operand; the result is an lvalue if its right operand is.
to
The type and value of the result are the type and value of the right operand; the result is an lvalue if the right operand is an lvalue, and is a bit-field if the right operand is an lvalue and a bit-field.

Relevant related text (no changes required):

7.6.2.2 [expr.unary.op] paragraph 4:

The operand of & shall not be a bit-field.

9.4.4 [dcl.init.ref] paragraph 5, bullet 1, sub-bullet 1 (regarding binding a reference to an lvalue):

... is an lvalue (but is not a bit-field) ...




659. Alignment of function types

Section: 7.6.2.6  [expr.alignof]     Status: CD1     Submitter: Alisdair Meredith     Date: 7 November 2007

[Voted into the WP at the September, 2008 meeting.]

The specification for the alignof operator (7.6.2.6 [expr.alignof]) does not forbid function types as operands, although it probably should.

Proposed resolution (March, 2008):

The issue, as described, is incorrect. The requirement in 7.6.2.6 [expr.alignof] is for “a complete object type,” so a function type is already forbidden. However, the existing text does have a problem in this requirement in that it does not allow a reference type, as anticipated by paragraph 3. Consequently, the proposal is to change 7.6.2.6 [expr.alignof] paragraph 1 as indicated:

An alignof expression yields the alignment requirement of its operand type. The operand shall be a type-id representing a complete object type or a reference to a complete object type.



256. Overflow in size calculations

Section: 7.6.2.8  [expr.new]     Status: CD1     Submitter: James Kanze     Date: 15 Oct 2000

[Voted into the WP at the September, 2008 meeting.]

[Picked up by evolution group at October 2002 meeting.]

(See also issue 476.)

The size requested by an array allocation is computed by multiplying the number of elements requested by the size of each element and adding an implementation-specific amount for overhead. It is possible for this calculation to overflow. Is an implementation required to detect this situation and, for instance, throw std::bad_alloc?

On one hand, the maximum allocation size is one of the implementation limits specifically mentioned in Annex Clause Annex B [implimits], and, according to 4.1 [intro.compliance] paragraph 2, an implementation is only required to "accept and correctly execute" programs that do not violate its resource limits.

On the other hand, it is difficult or impossible for user code to detect such overflows in a portable fashion, especially given that the array allocation overhead is not fixed, and it would be a service to the user to handle this situation gracefully.

Rationale (04/01):

Each implementation is required to document the maximum size of an object (Annex Clause Annex B [implimits]). It is not difficult for a program to check array allocations to ensure that they are smaller than this quantity. Implementations can provide a mechanism in which users concerned with this problem can request extra checking before array allocations, just as some implementations provide checking for array index and pointer validity. However, it would not be appropriate to require this overhead for every array allocation in every program.

(See issue 624 for a request to reconsider this resolution.)

Note (March, 2008):

The Evolution Working Group has accepted the intent of this issue and referred it to CWG for action for C++0x (see paper J16/07-0033 = WG21 N2173).

Proposed resolution (September, 2008):

This issue is resolved by the resolution of issue 624, given in paper N2757.




299. Conversion on array bound expression in new

Section: 7.6.2.8  [expr.new]     Status: CD1     Submitter: Mark Mitchell     Date: 19 Jul 2001

[Voted into WP at October 2005 meeting.]

In 7.6.2.8 [expr.new], the standard says that the expression in an array-new has to have integral type. There's already a DR (issue 74) that says it should also be allowed to have enumeration type. But, it should probably also say that it can have a class type with a single conversion to integral type; in other words the same thing as in 8.5.3 [stmt.switch] paragraph 2.

Suggested resolution:

In 7.6.2.8 [expr.new] paragraph 6, replace "integral or enumeration type (6.8.2 [basic.fundamental])" with "integral or enumeration type (6.8.2 [basic.fundamental]), or a class type for which a single conversion function to integral or enumeration type exists".

Proposed resolution (October, 2004):

Change 7.6.2.8 [expr.new] paragraph 6 as follows:

Every constant-expression in a direct-new-declarator shall be an integral constant expression (7.7 [expr.const]) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have be of integral type, or enumeration type (3.9.1), or a class type for which a single conversion function to integral or enumeration type exists (11.4.8 [class.conv]). If the expression is of class type, the expression is converted by calling the conversion function, and the result of the conversion is used in place of the original expression. The value of the expression shall bewith a non-negative value. [Example: ...

Proposed resolution (April, 2005):

Change 7.6.2.8 [expr.new] paragraph 6 as follows:

Every constant-expression in a direct-new-declarator shall be an integral constant expression (7.7 [expr.const]) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (6.8.2 [basic.fundamental]) with a non-negative value be of integral type, enumeration type, or a class type for which a single conversion function to integral or enumeration type exists (11.4.8 [class.conv]). If the expression is of class type, the expression is converted by calling that conversion function, and the result of the conversion is used in place of the original expression. If the value of the expression is negative, the behavior is undefined. [Example: ...



429. Matching deallocation function chosen based on syntax or signature?

Section: 7.6.2.8  [expr.new]     Status: CD1     Submitter: John Wilkinson     Date: 18 July 2003

[Voted into WP at October 2004 meeting.]

What does this example do?

  #include <stdio.h>
  #include <stdlib.h>

  struct A {
        void* operator new(size_t alloc_size, size_t dummy=0) {
                printf("A::operator new()\n");
                return malloc(alloc_size);
        };

        void operator delete(void* p, size_t s) {
                printf("A::delete %d\n", s);
        };


        A()  {printf("A constructing\n"); throw 2;};

  };

  int
  main() {
    try {
        A* ap = new A;
        delete ap;
    }
    catch(int) {printf("caught\n"); return 1;}
  }

The fundamental issue here is whether the deletion-on-throw is driven by the syntax of the new (placement or non-placement) or by signature matching. If the former, the operator delete would be called with the second argument equal to the size of the class. If the latter, it would be called with the second argument 0.

Core issue 127 (in TC1) dealt with this topic. It removed some wording in 14.3 [except.ctor] paragraph 2 that implied a syntax-based interpretation, leaving wording in 7.6.2.8 [expr.new] paragraph 19 that is signature-based. But there is no accompanying rationale to confirm an explicit choice of the signature-based approach.

EDG and g++ get 0 for the second argument, matching the presumed core issue 127 resolution. But maybe this should be revisited.

Notes from October 2003 meeting:

There was widespread agreement that the compiler shouldn't just silently call the delete with either of the possible values. In the end, we decided it's smarter to issue an error on this case and force the programmer to say what he means.

Mike Miller's analysis of the status quo: 6.7.5.5.3 [basic.stc.dynamic.deallocation] paragraph 2 says that "operator delete(void*, std::size_t)" is a "usual (non-placement) deallocation function" if the class does not declare "operator delete(void*)." 6.7.5.5.2 [basic.stc.dynamic.allocation] does not use the same terminology for allocation functions, but the most reasonable way to understand the uses of the term "placement allocation function" in the Standard is as an allocation function that has more than one parameter and thus can (but need not) be called using the "new-placement" syntax described in 7.6.2.8 [expr.new]. (In considering issue 127, the core group discussed and endorsed the position that, "If a placement allocation function has default arguments for all its parameters except the first, it can be called using non-placement syntax.")

7.6.2.8 [expr.new] paragraph 19 says that any non-placement deallocation function matches a non-placement allocation function, and that a placement deallocation function matches a placement allocation function with the same parameter types after the first -- i.e., a non-placement deallocation function cannot match a placement allocation function. This makes sense, because non-placement ("usual") deallocation functions expect to free memory obtained from the system heap, which might not be the case for storage resulting from calling a placement allocation function.

According to this analysis, the example shows a placement allocation function and a non-placement deallocation function, so the deallocation function should not be invoked at all, and the memory will just leak.

Proposed Resolution (October 2003):

Add the following text at the end of 7.6.2.8 [expr.new] paragraph 19:

If the lookup finds the two-parameter form of a usual deallocation function (6.7.5.5.3 [basic.stc.dynamic.deallocation]), and that function, considered as a placement deallocation function, would have been selected as a match for the allocation function, the program is ill-formed. [Example:
struct S {
  // Placement allocation function:
  static void* operator new(std::size_t, std::size_t);

  // Usual (non-placement) deallocation function:
  static void operator delete(void*, std::size_t);
};

S* p = new (0) S; // ill-formed: non-placement deallocation function matches 
                  // placement allocation function 
--- end example]



624. Overflow in calculating size of allocation

Section: 7.6.2.8  [expr.new]     Status: CD1     Submitter: Jens Maurer     Date: 8 March 2007

[Voted into the WP at the September, 2008 meeting (resolution in paper N2757).]

Issue 256 was closed without action, principally on the the grounds that an implementation could provide a means (command-line option, #pragma, etc.) for requesting that the allocation size be checked for validity, but that “it would not be appropriate to require this overhead for every array allocation in every program.”

This rationale may be giving too much weight to the overhead such a check would add, especially when compared to the likely cost of actually doing the storage allocation. In particular, the test essentially amounts to something like

    if (max_allocation_size / sizeof(T) < num_elements)
        throw std::bad_alloc();

(noting that max_allocation_size/sizeof(T) is a compile-time constant). It might make more sense to turn the rationale around and require the check, assuming that implementations could provide a mechanism for suppressing it if needed.

Suggested resolution:

In 7.6.2.8 [expr.new] paragraph 7, add the following words before the example:

If the value of the expression is such that the size of the allocated object would exceed the implementation-defined limit, an exception of type std::bad_alloc is thrown and no storage is obtained.

Note (March, 2008):

The Evolution Working Group has accepted the intent of issue 256 and referred it to CWG for action for C++0x (see paper J16/07-0033 = WG21 N2173).

Proposed resolution (March, 2008):

As suggested.

Notes from the June, 2008 meeting:

The CWG felt that this situation should not be treated like an out-of-memory situation and thus an exception of type std::bad_alloc (or, alternatively, returning a null pointer for a throw() allocator) would not be appropriate.

Proposed resolution (June, 2008):

Change 7.6.2.8 [expr.new] paragraph 8 as follows:

If the value of the expression in a direct-new-declarator is such that the size of the allocated object would exceed the implementation-defined limit, no storage is obtained and the new-expression terminates by throwing an exception of a type that would match a handler (14.4 [except.handle]) of type std::length_error (19.2.6 [length.error]). Otherwise, if When the value of the that expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

[Drafting note: std::length_error is thrown by std::string and std::vector and thus appears to be the right choice for the exception to be thrown here.]




288. Misuse of "static type" in describing pointers

Section: 7.6.2.9  [expr.delete]     Status: CD1     Submitter: James Kuyper     Date: 19 May 2001

[Voted into the WP at the June, 2008 meeting.]

For delete expressions, 7.6.2.9 [expr.delete] paragraph 1 says

The operand shall have a pointer type, or a class type having a single conversion function to a pointer type.

However, paragraph 3 of that same section says:

if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

Since the operand must be of pointer type, its static type is necessarily the same as its dynamic type. That clause is clearly referring to the object being pointed at, and not to the pointer operand itself.

Correcting the wording gets a little complicated, because dynamic and static types are attributes of expressions, not objects, and there's no sub-expression of a delete-expression which has the relevant types.

Suggested resolution:

then there is a static type and a dynamic type that the hypothetical expression (* const-expression) would have. If that static type is different from that dynamic type, then that static type shall be a base class of that dynamic type, and that static type shall have a virtual destructor, or the behavior is undefined.

There's precedent for such use of hypothetical constructs: see 7.6.10 [expr.eq] paragraph 2, and 9.3.2 [dcl.name] paragraph 1.

11.7.3 [class.virtual] paragraph 3 has a similar problem. It refers to

the type of the pointer or reference denoting the object (the static type).

The type of the pointer is different from the type of the reference, both of which are different from the static type of '*pointer', which is what I think was actually intended. Paragraph 6 contains the exact same wording, in need of the same correction. In this case, perhaps replacing "pointer or reference" with "expression" would be the best fix. In order for this fix to be sufficient, pointer->member must be considered equivalent to (*pointer).member, in which case the "expression" referred to would be (*pointer).

11.4.11 [class.free] paragraph 4 says that
if a delete-expression is used to deallocate a class object whose static type has...

This should be changed to

if a delete-expression is used to deallocate a class object through a pointer expression whose dereferenced static type would have...

The same problem occurs later, when it says that the

static and dynamic types of the object shall be identical

In this case you could replace "object" with "dereferenced pointer expression".

Footnote 104 says that

7.6.2.9 [expr.delete] requires that ... the static type of the delete-expression's operand be the same as its dynamic type.

This would need to be changed to

the delete-expression's dereferenced operand

Proposed resolution (December, 2006):

  1. Change 7.6.2.9 [expr.delete] paragraph 3 as follows:

  2. In the first alternative (delete object), if the static type of the operand object to be deleted is different from its dynamic type, the static type shall be a base class of the operand's dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
  3. Change the footnote in 11.4.11 [class.free] paragraph 4 as follows:

  4. A similar provision is not needed for the array version of operator delete because 7.6.2.9 [expr.delete] requires that in this situation, the static type of the delete-expression's operand object to be deleted be the same as its dynamic type.
  5. Change the footnote in 11.4.11 [class.free] paragraph 5 as follows:

  6. If the static type in the delete-expression of the object to be deleted is different from the dynamic type and the destructor is not virtual the size might be incorrect, but that case is already undefined; see 7.6.2.9 [expr.delete].

[Drafting notes: No change is required for 11.7.3 [class.virtual] paragraph 7 because “the type of the pointer” includes the pointed-to type. No change is required for 11.4.11 [class.free] paragraph 4 because “...used to deallocate a class object whose static type...” already refers to the object (and not the operand expression).]




353. Is deallocation routine called if destructor throws exception in delete?

Section: 7.6.2.9  [expr.delete]     Status: CD1     Submitter: Duane Smith     Date: 30 April 2002

[Voted into WP at April 2003 meeting.]

In a couple of comp.std.c++ threads, people have asked whether the Standard guarantees that the deallocation function will be called in a delete-expression if the destructor throws an exception. Most/all people have expressed the opinion that the deallocation function must be called in this case, although no one has been able to cite wording in the Standard supporting that view.

#include <new.h>
#include <stdio.h>
#include <stdlib.h>

static int flag = 0;

inline
void operator delete(void* p) throw()
{
   if (flag)
        printf("in deallocation function\n");
   free(p);
}

struct S {
    ~S() { throw 0; }
};

void f() {
    try {
        delete new S;
    }
    catch(...) { }
}

int main() {
       flag=1;
       f();
       flag=0;
       return 0;
}

Proposed resolution (October 2002):

Add to 7.6.2.9 [expr.delete] paragraph 7 the highlighted text:

The delete-expression will call a deallocation function (6.7.5.5.3 [basic.stc.dynamic.deallocation]) [Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception. ]



442. Incorrect use of null pointer constant in description of delete operator

Section: 7.6.2.9  [expr.delete]     Status: CD1     Submitter: Matthias Hofmann     Date: 2 Dec 2003

[Voted into WP at October 2005 meeting.]

After some discussion in comp.lang.c++.moderated we came to the conclusion that there seems to be a defect in 7.6.2.9 [expr.delete]/4, which says:

The cast-expression in a delete-expression shall be evaluated exactly once. If the delete-expression calls the implementation deallocation function (3.7.3.2), and if the operand of the delete expression is not the null pointer constant, the deallocation function will deallocate the storage referenced by the pointer thus rendering the pointer invalid. [Note: the value of a pointer that refers to deallocated storage is indeterminate. ]

In the second sentence, the term "null pointer constant" should be changed to "null pointer". In its present form, the passage claims that the deallocation function will deallocate the storage refered to by a null pointer that did not come from a null pointer constant in the delete expression. Besides, how can the null pointer constant be the operand of a delete expression, as "delete 0" is an error because delete requires a pointer type or a class type having a single conversion function to a pointer type?

See also issue 348.

Proposed resolution:

Change the indicated sentence of 7.6.2.9 [expr.delete] paragraph 4 as follows:

If the delete-expression calls the implementation deallocation function (6.7.5.5.3 [basic.stc.dynamic.deallocation]), and if the value of the operand of the delete expression is not the a null pointer constant, the deallocation function will deallocate the storage referenced by the pointer thus rendering the pointer invalid.

Notes from October 2004 meeting:

This wording is superseded by, and this issue will be resolved by, the resolution of issue 348.

Proposed resolution (April, 2005):

This issue is resolved by the resolution of issue 348.




520. Old-style casts between incomplete class types

Section: 7.6.3  [expr.cast]     Status: CD1     Submitter: comp.std.c++     Date: 19 May 2005

[Voted into WP at April, 2007 meeting.]

7.6.3 [expr.cast] paragraph 6 says,

The operand of a cast using the cast notation can be an rvalue of type “pointer to incomplete class type”. The destination type of a cast using the cast notation can be “pointer to incomplete class type”. In such cases, even if there is a inheritance relationship between the source and destination classes, whether the static_cast or reinterpret_cast interpretation is used is unspecified.

The wording seems to allow the following:

  1. casting from void pointer to incomplete type

  2.     struct A;
        struct B;
    
        void *v;
        A *a = (A*)v; // allowed to choose reinterpret_cast
    
  3. variant application of static or reinterpret casting

  4.     B *b = (B*)a;    // compiler can choose static_cast here
        A *aa = (A*)b;   // compiler can choose reinterpret_cast here
        assert(aa == a); // might not hold
    
  5. ability to somehow choose static_cast

  6. It's not entirely clear how a compiler can choose static_cast as 7.6.3 [expr.cast] paragraph 6 seems to allow. I believe the intent of 7.6.3 [expr.cast] paragraph 6 is to force the use of reinterpret_cast when either are incomplete class types and static_cast iff the compiler knows both types and there is a non-ambiguous hierarchy-traversal between that cast (or maybe not, core issue 242 talks about this). I cannot see any other interpretation because it isn't intuitive, every compiler I've tried agrees with me, and neither standard pointer conversions (7.3.12 [conv.ptr] paragraph 3) nor static_cast (7.6.1.9 [expr.static.cast] paragraph 5) talk about incomplete class types. If the committee agrees with me, I would like to see 7.3.12 [conv.ptr] paragraph 3 and 7.6.1.9 [expr.static.cast] paragraph 5 explicitly disallow incomplete class types and the wording of 7.6.3 [expr.cast] paragraph 6 changed to not allow any other interpretation.

Proposed resolution (April, 2006):

Change 7.6.3 [expr.cast] paragraph 6 as indicated:

The operand of a cast using the cast notation can be an rvalue of type “pointer to incomplete class type.” The destination type of a cast using the cast notation can be “pointer to incomplete class type.” In such cases, even if there is a inheritance relationship between the source and destination classes, whether the static_cast or reinterpret_cast interpretation is used is unspecified. If both the operand and destination types are class types and one or both are incomplete, it is unspecified whether the static_cast or the reinterpret_cast interpretation is used, even if there is an inheritance relationship between the two classes. [Note: For example, if the classes were defined later in the translation unit, a multi-pass compiler would be permitted to interpret a cast between pointers to the classes as if the class types were complete at that point. —end note]



497. Missing required initialization in example

Section: 7.6.4  [expr.mptr.oper]     Status: CD1     Submitter: Giovanni Bajo     Date: 03 Jan 2005

[Voted into WP at October 2005 meeting.]

7.6.4 [expr.mptr.oper] paragraph 5 contains the following example:

    struct S {
        mutable int i;
    };
    const S cs;
    int S::* pm = &S::i;   // pm refers to mutable member S::i
    cs.*pm = 88;           // ill-formed: cs is a const object

The const object cs is not explicitly initialized, and class S does not have a user-declared default constructor. This makes the code ill-formed as per 9.4 [dcl.init] paragraph 9.

Proposed resolution (April, 2005):

Change the example in 7.6.4 [expr.mptr.oper] paragraph 5 to read as follows:

    struct S {
        S() : i(0) { }
        mutable int i;
    };
    void f()
    {
        const S cs;
        int S::* pm = &S::i;   // pm refers to mutable member S::i
        cs.*pm = 88;           // ill-formed: cs is a const object
    }



614. Results of integer / and %

Section: 7.6.5  [expr.mul]     Status: CD1     Submitter: Gabriel Dos Reis     Date: 15 January 2007

[Voted into the WP at the September, 2008 meeting as part of paper N2757.]

The current Standard leaves it implementation-defined whether integer division rounds the result toward 0 or toward negative infinity and thus whether the result of % may be negative. C99, apparently reflecting (nearly?) unanimous hardware practice, has adopted the rule that integer division rounds toward 0, thus requiring that the result of -1 % 5 be -1. Should the C++ Standard follow suit?

On a related note, does INT_MIN % -1 invoke undefined behavior? The % operator is defined in terms of the / operator, and INT_MIN / -1 overflows, which by Clause 7 [expr] paragraph 5 causes undefined behavior; however, that is not the “result” of the % operation, so it's not clear. The wording of 7.6.5 [expr.mul] paragraph 4 appears to allow % to cause undefined behavior only when the second operand is 0.

Proposed resolution (August, 2008):

Change 7.6.5 [expr.mul] paragraph 4 as follows:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined. [Footnote: According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero. —end footnote]. For integral operands, the / operator yields the algebraic quotient with any fractional part discarded; [Footnote: This is often called “truncation towards zero.” —end footnote] if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

[Drafting note: see C99 6.5.5 paragraph 6.]




661. Semantics of arithmetic comparisons

Section: 7.6.9  [expr.rel]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 27 November 2007

[Voted into the WP at the June, 2008 meeting.]

The actual semantics of arithmetic comparison — e.g., whether 1 < 2 yields true or false — appear not to be specified anywhere in the Standard. The C Standard has a general statement that

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.

There is no corresponding statement in the C++ Standard.

Proposed resolution (February, 2008):

  1. Append the following paragraph to the end of 7.6.9 [expr.rel]:

  2. If both operands (after conversions) are of arithmetic type, each of the operators shall yield true if the specified relation is true and false if it is false.
  3. Append the following paragraph to the end of 7.6.10 [expr.eq]:

  4. Each of the operators shall yield true if the specified relation is true and false if it is false.



446. Does an lvalue-to-rvalue conversion on the "?" operator produce a temporary?

Section: 7.6.16  [expr.cond]     Status: CD1     Submitter: John Potter     Date: 31 Dec 2003

[Voted into WP at October 2005 meeting.]

The problem occurs when the value of the operator is determined to be an rvalue, the selected argument is an lvalue, the type is a class type and a non-const member is invoked on the modifiable rvalue result.

    struct B {
        int v;
        B (int v) : v(v) { }
        void inc () { ++ v; }
        };
    struct D : B {
        D (int v) : B(v) { }
        };

    B b1(42);
    (0 ? B(13) : b1).inc();
    assert(b1.v == 42);

The types of the second and third operands are the same and one is an rvalue. Nothing changes until p6 where an lvalue to rvalue conversion is performed on the third operand. 6.7.7 [class.temporary] states that an lvalue to rvalue conversion produces a temporary and there is nothing to remove it. It seems clear that the assertion must pass, yet most implementations fail.

There seems to be a defect in p3 b2 b1. First, the conditions to get here and pass the test.

If E1 and E2 have class type, and the underlying class types are the same or one is a base class of the other: E1 can be converted to match E2 if the class of T2 is the same type as, or a base class of, the class of T1, and the cv-qualification of T2 is the same cv-qualification as, or a greater cv-qualification than, the cv-qualification of T1.

If both E1 and E2 are lvalues, passing the conditions here also passes the conditions for p3 b1. Thus, at least one is an rvalue. The case of two rvalues is not interesting and the action is covered by the case when E1 is an rvalue.

    (0 ? D(13) : b1).inc();
    assert(b1.v == 42);
E1 is changed to an rvalue of type T2 that still refers to the original source class object (or the appropriate subobject thereof). [Note: that is, no copy is made. ]

Having changed the rvalue to base type, we are back to the above case where an lvalue to rvalue conversion is required on the third operand at p6. Again, most implementations fail.

The remaining case, E1 an lvalue and E2 an rvalue, is the defect.

    D d1(42);
    (0 ? B(13) : d1).inc();
    assert(d1.v == 42);

The above quote states that an lvalue of type T1 is changed to an rvalue of type T2 without creating a temporary. This is in contradiction to everything else in the standard about lvalue to rvalue conversions. Most implementations pass in spite of the defect.

The usual accessible and unambiguous is missing from the base class.

There seems to be two possible solutions. Following other temporary creations would produce a temporary rvalue of type T1 and change it to an rvalue of type T2. Keeping the no copy aspect of this bullet intact would change the lvalue of type T1 to an lvalue of type T2. In this case the lvalue to rvalue conversion would happen in p6 as usual.

Suggested wording for p3 b2 b1

The base part:

If E1 and E2 have class type, and the underlying class types are the same or one is a base class of the other: E1 can be converted to match E2 if the class of T2 is the same type as, or an accessible and unambiguous base class of, the class of T1, and the cv-qualification of T2 is the same cv-qualification as, or a greater cv-qualification than, the cv-qualification of T1. If the conversion is applied:

The same type temporary version:

If E1 is an lvalue, an lvalue to rvalue conversion is applied. The resulting or original rvalue is changed to an rvalue of type T2 that refers to the same class object (or the appropriate subobject thereof). [Note: that is, no copy is made in changing the type of the rvalue. ]

The never copy version:

The lvalue(rvalue) E1 is changed to an lvalue(rvalue) of type T2 that refers to the original class object (or the appropriate subobject thereof). [Note: that is, no copy is made. ]

The test case was posted to clc++m and results for implementations were reported.

#include <cassert>
struct B {
    int v;
    B (int v) : v(v) { }
    void inc () { ++ v; }
    };
struct D : B {
    D (int v) : B(v) { }
    };
int main () {
    B b1(42);
    D d1(42);
    (0 ? B(13) : b1).inc();
    assert(b1.v == 42);
    (0 ? D(13) : b1).inc();
    assert(b1.v == 42);
    (0 ? B(13) : d1).inc();
    assert(d1.v == 42);
    }

// CbuilderX(EDG301) FFF  Rob Williscroft
// ICC-8.0           FFF  Alexander Stippler
// COMO-4.301        FFF  Alexander Stippler

// BCC-5.4           FFP  Rob Williscroft
// BCC32-5.5         FFP  John Potter
// BCC32-5.65        FFP  Rob Williscroft
// VC-6.0            FFP  Stephen Howe
// VC-7.0            FFP  Ben Hutchings
// VC-7.1            FFP  Stephen Howe
// OpenWatcom-1.1    FFP  Stephen Howe

// Sun C++-6.2       PFF  Ron Natalie

// GCC-3.2           PFP  John Potter
// GCC-3.3           PFP  Alexander Stippler

// GCC-2.95          PPP  Ben Hutchings
// GCC-3.4           PPP  Florian Weimer

I see no defect with regards to lvalue to rvalue conversions; however, there seems to be disagreement about what it means by implementers. It may not be surprising because 5.16 and passing a POD struct to an ellipsis are the only places where an lvalue to rvalue conversion applies to a class type. Most lvalue to rvalue conversions are on basic types as operands of builtin operators.

Notes from the March 2004 meeting:

We decided all "?" operators that return a class rvalue should copy the second or third operand to a temporary. See issue 86.

Proposed resolution (October 2004):

  1. Change 7.6.16 [expr.cond] bullet 3.2 sub-bullet 1 as follows:

    if E1 and E2 have class type, and the underlying class types are the same or one is a base class of the other: E1 can be converted to match E2 if the class of T2 is the same type as, or a base class of, the class of T1, and the cv-qualification of T2 is the same cv-qualification as, or a greater cv-qualification than, the cv-qualification of T1. If the conversion is applied, E1 is changed to an rvalue of type T2 that still refers to the original source class object (or the appropriate subobject thereof). [Note: that is, no copy is made. —end note] by copy-initializing a temporary of type T2 from E1 and using that temporary as the converted operand.
  2. Change 7.6.16 [expr.cond] bullet 6.1 as follows:

    The second and third operands have the same type; the result is of that type. If the operands have class type, the result is an rvalue temporary of the result type, which is copy-initialized from either the second operand or the third operand depending on the value of the first operand.
  3. Change 7.3.2 [conv.lval] paragraph 2 as follows:

    The value contained in the object indicated by the lvalue is the rvalue result. When an lvalue-to-rvalue conversion occurs within the operand of sizeof (7.6.2.5 [expr.sizeof]) the value contained in the referenced object is not accessed, since that operator does not evaluate its operand. Otherwise, if the lvalue has a class type, the conversion copy-initializes a temporary of type T from the lvalue and the result of the conversion is an rvalue for the temporary. Otherwise, the value contained in the object indicated by the lvalue is the rvalue result.

[Note: this wording partially resolves issue 86. See also issue 462.]




339. Overload resolution in operand of sizeof in constant expression

Section: 7.7  [expr.const]     Status: CD1     Submitter: Steve Adamczyk     Date: 11 Mar 2002

[Voted into the WP at the June, 2008 meeting as paper N2634.]

I've seen some pieces of code recently that put complex expressions involving overload resolution inside sizeof operations in constant expressions in templates.

7.7 [expr.const] paragraph 1 implies that some kinds of nonconstant expressions are allowed inside a sizeof in a constant expression, but it's not clear that this was intended to extend all the way to things like overload resolution. Allowing such things has some hidden costs. For example, name mangling has to be able to represent all operators, including calls, and not just the operators that can appear in constant expressions.

  template <int I> struct A {};

  char xxx(int);
  char xxx(float);

  template <class T> A<sizeof(xxx((T)0))> f(T){}

  int main()
  {
    f(1);
  }

If complex expressions are indeed allowed, it should be because of an explicit committee decision rather than because of some looseness in this section of the standard.

Notes from the 4/02 meeting:

Any argument for restricting such expressions must involve a cost/benefit ratio: a restriction would be palatable only if it causes minimum hardship for users and allows a substantial reduction in implementation cost. If we propose a restriction, it must be one that library writers can live with.

Lots of these cases fail with current compilers, so there can't be a lot of existing code using them. We plan to find out what cases there are in libraries like Loki and Boost.

We noted that in many cases one can move the code into a class to get the same result. The implementation problem comes up when the expression-in-sizeof is in a template deduction context or part of a template signature. The problem cases are ones where an error causes deduction to fail, as opposed to contexts where an error causes a diagnostic. The latter contexts are easier to handle; however, there are situations where "fail deduction" may be the desired behavior.

Notes from the April 2003 meeting:

Here is a better example:

  extern "C" int printf(const char *, ...);
  char f(int);
  int f(...);
  // Approach 1 -- overload resolution in template class
  // No problem
  template <class T> struct conv_int {
    static const bool value = (sizeof(f(T())) == 1);
  };
  // Approach 2 -- overload resolution in type deduction
  // Difficult
  template <int I> struct A {
    static const int value = I;
  };
  template <class T> bool conv_int2(A<sizeof(f(T()))> p) {
    return p.value == 1;
  }

  template<typename T>
  A<sizeof(f(T()))> make_A() {
    return A<sizeof(f(T()))>();
  }

  int main() {
    printf("short: %d\n", conv_int<short>::value);
    printf("int *: %d\n", conv_int<int *>::value);
    printf("short: %d\n", conv_int2<short>(make_A<short>()));
    printf("int *: %d\n", conv_int2<int *>(make_A<int*>()));
  }

The core working group liked the idea of a restriction that says that expressions inside sizeof in template signature contexts must be otherwise valid as nontype template argument expressions (i.e., integer operations only, limited casts). This of course is subject to whether users can live with that restriction. This topic was brought up in full committee, but there was limited feedback from other groups.

It was also noted that if typeof (whatever it is called) is added, there may be a similar issue there.

Note (March, 2005):

Dave Abrahams (quoting a Usenet posting by Vladimir Marko): The decltype and auto proposal (revision 3: N1607) presents

    template <class T,class U>
    decltype((*(T*)0)+(*(U*)0)) add(const T& t,const U& u);

as a valid declaration (if the proposal is accepted). If [the restrictions in the April, 2003 note] really applied to decltype, the declaration above would be invalid. AFAICT every non-trivial use of decltype in a template function declaration would be invalid. And for me this would render my favorite proposal useless.

I would propose to allow any kind of expression inside sizeof (and decltype) and explicitly add sizeof (and decltype) expressions involving template-parameters to non-deduced contexts (add a bullet to 13.10.3.5 [temp.deduct.partial] paragraph 4).

Jaakko Jarvi: Just reinforcing that this is important and hope for insights. The topic is discussed a bit on page 10 of the latest revision of the proposal (N1705). Here's a quote from the proposal:

However, it is crucial that no restrictions are placed on what kinds of expressions are allowed inside decltype, and therefore also inside sizeof. We suggest that issue 339 is resolved to require the compiler to fail deduction (apply the SFINAE principle), and not produce an error, for as large set of invalid expressions in operands of sizeof or decltype as is possible to comfortably implement. We wish that implementors aid in classifying the kinds of expressions that should produce errors, and the kinds that should lead to failure of deduction.

Notes from the April, 2007 meeting:

The CWG is pursuing a compromise proposal, to which the EWG has tentatively agreed, which would allow arbitrary expressions in the return types of function templates but which would restrict the expressions that participate in the function signature (and thus in overload resolution) to those that can be used as non-type template arguments. During deduction and overload resolution, these complex return types would be ignored; that is, there would be no substitution of the deduced template arguments into the return type at this point. If such a function were selected by overload resolution, however, a substitution failure in the return type would produce a diagnostic rather than a deduction failure.

This approach works when doing overload resolution in the context of a function call, but additional tricks (still being defined) are needed in other contexts such as friend function declaration matching and taking the address of a function, in which the return type does play a part.

Notes from the July, 2007 meeting:

The problem is whether arbitrary expressions (for example, ones that include overload resolution) are allowed in template deduction contexts, and, if so, which expression errors are SFINAE failures and which are hard errors.

This issue deals with arbitrary expressions inside sizeof in deduction contexts. That's a fringe case right now (most compilers don't accept them). decltype makes the problem worse, because the standard use case is one that involves overload resolution. Generalized constant expressions make it worse yet, because they allow overload resolution and class types to show up in any constant expression in a deduction context.

Why is this an issue? Why don't we just say everything is allowed and be done with it?

At the April, 2007 meeting, we were headed toward a solution that imposed a restriction on expressions in deduction contexts, but such a restriction seems to really hamper uses of constexpr functions. So we're now proposing that fully general expressions be allowed, and that most errors in such expressions be treated as SFINAE failures rather than errors.

One issue with writing Standard wording for that is how to define “most.” There's a continuum of errors, some errors being clearly SFINAE failures, and some clearly “real” errors, with lots of unclear cases in between. We decided it's easier to write the definition by listing the errors that are not treated as SFINAE failures, and the list we came up with is as follows:

  1. errors that occur while processing some entity external to the expression, e.g., an instantiation of a template or the generation of the definition of an implicitly-declared copy constructor
  2. errors due to implementation limits
  3. errors due to access violations (this is a judgment call, but the philosophy of access has always been that it doesn't affect visibility)

Everything else produces a SFINAE failure rather than a hard error.

There was broad consensus that this felt like a good solution, but that feeling was mixed with trepidation on several fronts:

We will be producing wording for the Working Draft for the October, 2007 meeting.

(See also issue 657.)




366. String literal allowed in integral constant expression?

Section: 7.7  [expr.const]     Status: CD1     Submitter: Martin v. Loewis     Date: 29 July 2002

[Voted into WP at October 2003 meeting.]

According to 15.2 [cpp.cond] paragraph 1, the if-group

#if "Hello, world"

is well-formed, since it is an integral constant expression. Since that may not be obvious, here is why:

7.7 [expr.const] paragraph 1 says that an integral constant expression may involve literals (5.13 [lex.literal]); "Hello, world" is a literal. It restricts operators to not use certain type conversions; this expression does not use type conversions. It further disallows functions, class objects, pointers, ... - this expression is none of those, since it is an array.

However, 15.2 [cpp.cond] paragraph 6 does not explain what to do with this if-group, since the expression evaluates neither to false(zero) nor true(non-zero).

Proposed resolution (October 2002):

Change the beginning of the second sentence of 7.7 [expr.const] paragraph 1 which currently reads

An integral constant-expression can involve only literals (5.13 [lex.literal]), ...
to say
An integral constant-expression can involve only literals of arithmetic types (5.13 [lex.literal], 6.8.2 [basic.fundamental]), ...




367. throw operator allowed in constant expression?

Section: 7.7  [expr.const]     Status: CD1     Submitter: Martin v. Loewis     Date: 29 July 2002

[Voted into WP at the October, 2006 meeting.]

The following translation unit appears to be well-formed.

int x[true?throw 4:5];

According to 7.7 [expr.const], this appears to be an integral constant expression: it is a conditional expression, involves only literals, and no assignment, increment, decrement, function-call, or comma operators. However, if this is well-formed, the standard gives no meaning to this declaration, since the array bound (9.3.4.5 [dcl.array] paragraph 1) cannot be computed.

I believe the defect is that throw expressions should also be banned from constant expressions.

Notes from October 2002 meeting:

We should also check on new and delete.

Notes from the April, 2005 meeting:

Although it could be argued that all three of these operators potentially involve function calls — throw to std::terminate, new and delete to the corresponding allocation and deallocation functions — and thus would already be excluded from constant expressions, this reasoning was considered to be too subtle to allow closing the issue with no change. A modification that explicitly clarifies the status of these operators will be drafted.

Proposed resolution (October, 2005):

Change the last sentence of 7.7 [expr.const] as indicated:

In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call function call (including new-expressions and delete-expressions), or comma operators, or throw-expressions shall not be used.

Note: this sentence is also changed by the resolution of issue 530.




457. Wording nit on use of const variables in constant expressions

Section: 7.7  [expr.const]     Status: CD1     Submitter: Mark Mitchell     Date: 03 Feb 2004

[Voted into WP at April 2005 meeting.]

I'm looking at 7.7 [expr.const]. I see:

An integral constant-expression can involve only ... const variables or static data members of integral or enumeration types initialized with constant expressions ...

Shouldn't that be "const non-volatile"?

It seems weird to say that:

  const volatile int i = 3;
  int j[i];
is valid.

Steve Adamczyk: See issue 76, which made the similar change to 9.2.9.2 [dcl.type.cv] paragraph 2, and probably should have changed this one as well.

Proposed resolution (October, 2004):

Change the first sentence in the second part of 7.7 [expr.const] paragraph 1 as follows:

An integral constant-expression can involve only literals of arithmetic types (5.13 [lex.literal], 6.8.2 [basic.fundamental]), enumerators, non-volatile const variables or static data members of integral or enumeration types initialized with constant expressions (9.4 [dcl.init]), non-type template parameters of integral or enumeration types, and sizeof expressions.



530. Nontype template arguments in constant expressions

Section: 7.7  [expr.const]     Status: CD1     Submitter: Mark Mitchell     Date: 21 August 2005

[Voted into the WP at the April, 2007 meeting as part of paper J16/07-0095 = WG21 N2235.]

Consider:

    template <int* p> struct S {
        static const int I = 3;
    };
    int i;
    int a[S<&i>::I];

Clearly this should be valid, but a pedantic reading of 7.7 [expr.const] would suggest that this is invalid because “&i” is not permitted in integral constant expressions.

Proposed resolution (October, 2005):

Change the last sentence of 7.7 [expr.const] paragraph 1 as indicated:

In particular, except in non-type template-arguments or sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used.

(Note: the same text is changed by the resolution of issue 367.)

Notes from April, 2006 meeting:

The proposed resolution could potentially be read as saying that the prohibited operations and operators would be permitted in integral constant expressions that are non-type template-arguments. John Spicer is investigating an alternate approach, to say that expressions in non-type template arguments are not part of the expression in which the template-id appears (in contrast to the operand of sizeof, which is part of the containing expression).

Additional note (May, 2008):

This issue is resolved by the rewrite of 7.7 [expr.const] that was done in conjunction with the constexpr proposal, paper N2235.




684. Constant expressions involving the address of an automatic variable

Section: 7.7  [expr.const]     Status: CD1     Submitter: Jens Maurer     Date: 13 March, 2008

[Voted into the WP at the September, 2008 meeting (resolution in paper N2757).]

The expressions that are excluded from being constant expressions in 7.7 [expr.const] paragraph 2 does not address an example like the following:

    void f() {
       int a;
       constexpr int* p = &a;    // should be ill-formed, currently isn't
    }

Suggested resolution:

Add the following bullet to the list in 7.7 [expr.const] paragraph 2:

Proposed resolution (June, 2008):

  1. Change 6.9.3.2 [basic.start.static] paragraph 1 as follows:

  2. Objects with static storage duration (6.7.5.2 [basic.stc.static]) or thread storage duration (3.7.2) shall be zero-initialized (9.4 [dcl.init]) before any other initialization takes place. A reference with static or thread storage duration and an object of trivial or literal type with static or thread storage duration can be initialized with a constant expression (7.7 [expr.const]); this is called constant initialization. Constant initialization is performed:
    • if an object of trivial or literal type with static or thread storage duration is initialized with a constant expression (7.7 [expr.const]), or

    • if a reference with static or thread storage duration is initialized with a constant expression that is not an lvalue designating an object with thread or automatic storage duration.

    Together, zero-initialization and constant initialization...
  3. Add the following in 7.7 [expr.const] paragraph 2:

(Note: the change to 6.9.3.2 [basic.start.static] paragraph 1 needs to be reconciled with the conflicting change in issue 688.)




276. Order of destruction of parameters and temporaries

Section: 8.7  [stmt.jump]     Status: CD1     Submitter: James Kanze     Date: 28 Mar 2001

[Voted into the WP at the June, 2008 meeting.]

According to 8.7 [stmt.jump] paragraph 2,

On exit from a scope (however accomplished), destructors (11.4.7 [class.dtor]) are called for all constructed objects with automatic storage duration (6.7.5.4 [basic.stc.auto]) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration.

This wording is problematic for temporaries and for parameters. First, temporaries are not "declared," so this requirement does not apply to them, in spite of the assertion in the quoted text that it does.

Second, although the parameters of a function are declared in the called function, they are constructed and destroyed in the calling context, and the order of evaluation of the arguments is unspecified (cf 7.6.1.3 [expr.call] paragraphs 4 and 8). The order of destruction of the parameters might, therefore, be different from the reverse order of their declaration.

Notes from 04/01 meeting:

Any resolution of this issue should be careful not to introduce requirements that are redundant or in conflict with those of other parts of the IS. This is especially true in light of the pending issues with respect to the destruction of temporaries (see issues 86, 124, 199, and 201). If possible, the wording of a resolution should simply reference the relevant sections.

It was also noted that the temporary for a return value is also destroyed "out of order."

Note that issue 378 picks a nit with the wording of this same paragraph.

Proposed Resolution (November, 2006):

Change 8.7 [stmt.jump] paragraph 2 as follows:

On exit from a scope (however accomplished), destructors (11.4.7 [class.dtor]) are called for all constructed objects with automatic storage duration (6.7.5.4 [basic.stc.auto]) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration. variables with automatic storage duration (6.7.5.4 [basic.stc.auto]) that have been constructed in that scope are destroyed in the reverse order of their construction. [Note: For temporaries, see 6.7.7 [class.temporary]. —end note] Transfer out of a loop...



378. Wording that says temporaries are declared

Section: 8.7  [stmt.jump]     Status: CD1     Submitter: Gennaro Prota     Date: 07 September 2002

Paragraph 8.7 [stmt.jump] paragraph 2 of the standard says:

On exit from a scope (however accomplished), destructors (11.4.7 [class.dtor]) are called for all constructed objects with automatic storage duration (6.7.5.4 [basic.stc.auto]) (named objects or temporaries) that are declared in that scope.

It refers to objects "that are declared" but the text in parenthesis also mentions temporaries, which cannot be declared. I think that text should be removed.

This is related to issue 276.

Proposed Resolution (November, 2006):

This issue is resolved by the resolution of issue 276.




281. inline specifier in friend declarations

Section: 9.2.3  [dcl.fct.spec]     Status: CD1     Submitter: John Spicer     Date: 24 Apr 2001

[Moved to DR at October 2002 meeting.]

There is currently no restriction on the use of the inline specifier in friend declarations. That would mean that the following usage is permitted:

    struct A {
        void f();
    };

    struct B {
        friend inline void A::f();
    };

    void A::f(){}

I believe this should be disallowed because a friend declaration in one class should not be able to change attributes of a member function of another class.

More generally, I think that the inline attribute should only be permitted in friend declarations that are definitions.

Notes from the 04/01 meeting:

The consensus agreed with the suggested resolution. This outcome would be similar to the resolution of issue 136.

Proposed resolution (10/01):

Add to the end of 9.2.3 [dcl.fct.spec] paragraph 3:

If the inline specifier is used in a friend declaration, that declaration shall be a definition or the function shall have previously been declared inline.



317. Can a function be declared inline after it has been called?

Section: 9.2.3  [dcl.fct.spec]     Status: CD1     Submitter: Steve Clamage     Date: 14 Oct 2001

[Voted into WP at October 2005 meeting.]

Steve Clamage: Consider this sequence of declarations:

  void foo() { ... }
  inline void foo();
The non-inline definition of foo precedes the inline declaration. It seems to me this code should be ill-formed, but I could not find anything in the standard to cover the situation.

Bjarne Stroustrup: Neither could I, so I looked in the ARM, which addressed this case (apparently for member function only) in some detail in 7.1.2 (pp103-104).

The ARM allows declaring a function inline after its initial declaration, as long as it has not been called.

Steve Clamage: If the above code is valid, how about this:

  void foo() { ... }    // define foo
  void bar() { foo(); } // use foo
  inline void foo();    // declare foo inline

Bjarne Stroustrup: ... and [the ARM] disallows declaring a function inline after it has been called.

This may still be a good resolution.

Steve Clamage: But the situation in the ARM is the reverse: Declare a function inline, and define it later (with no intervening call). That's a long-standing rule in C++, and allows you to write member function definitions outside the class.

In my example, the compiler could reasonably process the entire function as out-of-line, and not discover the inline declaration until it was too late to save the information necessary for inline generation. The equivalent of another compiler pass would be needed to handle this situation.

Bjarne Stroustrup: I see, and I think your argument it conclusive.

Steve Clamage: I'd like to open a core issue on this point, and I recommend wording along the lines of: "A function defined without an inline specifier shall not be followed by a declaration having an inline specifier."

I'd still like to allow the common idiom

  class T {
    int f();
  };
  inline int T::f() { ... }

Martin Sebor: Since the inline keyword is just a hint to the compiler, I don't see any harm in allowing the construct. Your hypothetical compiler can simply ignore the inline on the second declaration. On the other hand, I feel that adding another special rule will unnecessarily complicate the language.

Steve Clamage: The inline specifier is more than a hint. You can have multiple definitions of inline functions, but only one definition of a function not declared inline. In particular, suppose the above example were in a header file, and included multiple times in a program.

Proposed resolution (October, 2004):

Add the indicated words to 9.2.3 [dcl.fct.spec] paragraph 4:

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (6.3 [basic.def.odr]). [Note: a call to the inline function may be encountered before its definition appears in the translation unit. —end note] If the definition of a function appears in a translation unit before its first declaration as inline, the program is ill-formed. If a function with external linkage is declared inline in one translation unit...



396. Misleading note regarding use of auto for disambiguation

Section: 9.2.3  [dcl.fct.spec]     Status: CD1     Submitter: Herb Sutter     Date: 3 Jan 2003

[Voted into WP at March 2004 meeting.]

BTW, I noticed that the following note in 9.2.2 [dcl.stc] paragraph 2 doesn't seem to have made it onto the issues list or into the TR:

[Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (stmt.ambig) explicitly. --- end note]

I thought that this was well known to be incorrect, because using auto does not disambiguate this. Writing:

  auto int f();
is still a declaration of a function f, just now with an error since the function's return type may not use an auto storage class specifier. I suppose an error is an improvement over a silent ambiguity going the wrong way, but it's still not a solution for the user who wants to express the other in a compilable way.

Proposed resolution: Replace that note with the following note:

[Note: hence, the auto specifier is always redundant and not often used. --- end note]

John Spicer: I support the proposed change, but I think the disambiguation case is not the one that you describe. An example of the supposed disambiguation is:

  int i;
  int j;
  int main()
  {
    int(i);  // declares i, not reference to ::i
    auto int(j);  // declares j, not reference to ::j
  }

cfront would take "int(i)" as a cast of ::i, so the auto would force what it would otherwise treat as a statement to be considered a declaration (cfront 3.0 warned that this would change in the future).

In a conforming compiler the auto is always redundant (as you say) because anything that could be considered a valid declaration should be treated as one.

Proposed resolution (April 2003):

Replace 9.2.2 [dcl.stc] paragraph 2

[Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (8.9 [stmt.ambig]) explicitly. --- end note]
with
[Note: hence, the auto specifier is always redundant and not often used. One use of auto is to distinguish a declaration-statement from an expression-statement explicitly rather than relying on the disambiguation rules (8.9 [stmt.ambig]), which may aid readers. --- end note]




397. Same address for string literals from default arguments in inline functions?

Section: 9.2.3  [dcl.fct.spec]     Status: CD1     Submitter: Mark Mitchell     Date: 13 Jan 2003

[Voted into WP at April, 2007 meeting.]

Are string literals from default arguments used in extern inlines supposed to have the same addresses across all translation units?

  void f(const char* = "s")
  inline g() {
    f();
  }

Must the "s" strings be the same in all copies of the inline function?

Steve Adamczyk: The totality of the standard's wisdom on this topic is (9.2.3 [dcl.fct.spec] paragraph 4):

A string literal in an extern inline function is the same object in different translation units.

I'd hazard a guess that a literal in a default argument expression is not "in" the extern inline function (it doesn't appear in the tokens of the function), and therefore it need not be the same in different translation units.

I don't know that users would expect such strings to have the same address, and an equally valid (and incompatible) expectation would be that the same string literal would be used for every expansion of a given default argument in a single translation unit.

Notes from April 2003 meeting:

The core working group feels that the address of a string literal should be guaranteed to be the same only if it actually appears textually within the body of the inline function. So a string in a default argument expression in a block extern declaration inside the body of a function would be the same in all instances of the function. On the other hand, a string in a default argument expression in the header of the function (i.e., outside of the body) would not be the same.

Proposed resolution (April 2003):

Change the last sentence and add the note to the end of 9.2.3 [dcl.fct.spec] paragraph 4:

A string literal in the body of an extern inline function is the same object in different translation units. [Note: A string literal that is encountered only in the context of a function call (in the default argument expression of the called function), is not “in” the extern inline function.]

Notes from October 2003 meeting:

We discussed ctor-initializer lists and decided that they are also part of the body. We've asked Clark Nelson to work on syntax changes to give us a syntax term for the body of a function so we can refer to it here. See also issue 452, which could use this term.

(October, 2005: moved to “review” status in concert with issue 452. With that resolution, the wording above needs no further changes.)

Proposed resolution (April, 2006):

Change the last sentence and add the note to the end of 9.2.3 [dcl.fct.spec] paragraph 4:

A string literal in the body of an extern inline function is the same object in different translation units. [Note: A string literal appearing in a default argument expression is not considered to be “in the body” of an inline function merely by virtue of the expression’s use in a function call from that inline function. —end note]



477. Can virtual appear in a friend declaration?

Section: 9.2.3  [dcl.fct.spec]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 23 Sep 2004

[Voted into WP at the October, 2006 meeting.]

I couldn't find wording that makes it invalid to say friend virtual... The closest seems to be 9.2.3 [dcl.fct.spec] paragraph 5, which says:

The virtual specifier shall only be used in declarations of nonstatic class member functions that appear within a member-specification of a class definition; see 11.7.3 [class.virtual].

I don't think that excludes a friend declaration (which is a valid member-specification by 11.4 [class.mem]).

John Spicer: I agree that virtual should not be allowed on friend declarations. I think the wording in 9.2.3 [dcl.fct.spec] is intended to be the declaration of a function within its class, although I think the wording should be improved to make it clearer.

Proposed resolution (October, 2005):

Change 9.2.3 [dcl.fct.spec] paragraphs 5-6 as indicated:

The virtual specifier shall only be used only in declarations the initial declaration of a non-static class member functions that appear within a member-specification of a class definition function; see 11.7.3 [class.virtual].

The explicit specifier shall be used only in declarations the declaration of constructors a constructor within a its class definition; see 11.4.8.2 [class.conv.ctor].




424. Wording problem with issue 56 resolution on redeclaring typedefs in class scope

Section: 9.2.4  [dcl.typedef]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 25 June 2003

[Voted into WP at March 2004 meeting.]

I wonder if perhaps the core issue 56 change in 9.2.4 [dcl.typedef] paragraph 2 wasn't quite careful enough. The intent was to remove the allowance for:

  struct S {
    typedef int I;
    typedef int I;
  };

but I think it also disallows the following:

  class B {
    typedef struct A {} A;
    void f(struct B::A*p);
  };

See also issue 407.

Proposed resolution (October 2003):

At the end of 9.2.4 [dcl.typedef] paragraph 2, add the following:

In a given class scope, a typedef specifier can be used to redefine any class-name declared in that scope that is not also a typedef-name to refer to the type to which it already refers. [Example:
  struct S {
    typedef struct A {} A;  // OK
    typedef struct B B;     // OK
    typedef A A;            // error
  };
]



647. Non-constexpr instances of constexpr constructor templates

Section: 9.2.6  [dcl.constexpr]     Status: CD1     Submitter: Mike Miller     Date: 12 Aug 2007

[Voted into the WP at the September, 2008 meeting.]

According to 9.2.6 [dcl.constexpr] paragraph 5,

If the instantiated template specialization of a constexpr function template would fail to satisfy the requirements for a constexpr function, the constexpr specifier is ignored and the specialization is not a constexpr function.

One would expect to see a similar provision for an instantiated constructor template (because the requirements for a constexpr function [paragraph 3] are different from the requirements for a constexpr constructor [paragraph 4]), but there is none; constexpr constructor templates are not mentioned.

Suggested resolution:

Change the wording of 9.2.6 [dcl.constexpr] paragraph 5 as indicated:

If the instantiated template specialization of a constexpr function template would fail to satisfy the requirements for a constexpr function or constexpr constructor, as appropriate to the function template, the constexpr specifier is ignored and the specialization is not a constexpr function or constexpr constructor.

Proposed resolution (June, 2008):

[Drafting note: This resolution goes beyond the problem described in the issue discussion, which is one aspect of the general failure of the existing wording to deal consistently with the distinctions between constexpr functions and constexpr constructors. The wording below attempts to rectify that problem systematically.]

  1. Change 9.2.6 [dcl.constexpr] paragraph 2 as follows:

  2. A constexpr specifier used in a function declaration the declaration of a function that is not a constructor declares that function to be a constexpr function. Similarly, a constexpr specifier used in a constructor declaration declares that constructor to be a constexpr constructor. Constexpr functions and constexpr constructors are implicitly inline (9.2.3 [dcl.fct.spec]). A constexpr function shall not be virtual (10.3).
  3. Change 9.2.6 [dcl.constexpr] paragraph 3 as follows:

  4. The definition of a constexpr function shall satisfy the following constraints:

    [Example:...

  5. Change 9.2.6 [dcl.constexpr] paragraph 4 as follows:

  6. The definition of a constexpr constructor shall satisfy the following constraints:

    A trivial copy constructor is also a constexpr constructor. [Example: ...

  7. Change 9.2.6 [dcl.constexpr] paragraph 5 as follows:

  8. If the instantiated template specialization of a constexpr function template would fail to satisfy the requirements for a constexpr function or constexpr constructor, the constexpr specifier is ignored and the specialization is not a constexpr function.
  9. Change 9.2.6 [dcl.constexpr] paragraph 6 as follows:

  10. A constexpr specifier used in for a non-static member function definition that is not a constructor declares that member function to be const (11.4.3 [class.mfct.non.static]). [Note: ...



648. Constant expressions in constexpr initializers

Section: 9.2.6  [dcl.constexpr]     Status: CD1     Submitter: Mike Miller     Date: 12 Aug 2007

[Voted into the WP at the September, 2008 meeting.]

The current wording of 9.2.6 [dcl.constexpr] paragraph 7 seems not quite correct. It reads,

A constexpr specifier used in an object declaration declares the object as const. Such an object shall be initialized, and every expression that appears in its initializer (9.4 [dcl.init]) shall be a constant expression.

The phrase “every expression” is intended to cover multiple arguments to a constexpr constructor and multiple expressions in an aggregate initializer. However, it could be read (incorrectly) as saying that non-constant expressions cannot appear as subexpressions in such initializers, even in places where they do not render the full-expression non-constant (i.e., as unevaluated operands and in the unselected branches of &&, ||, and ?:). Perhaps this problem could be remedied by replacing “every expression” with “every full-expression?”

Proposed resolution (June, 2008):

Change 9.2.6 [dcl.constexpr] paragraph 7 as follows:

A constexpr specifier used in an object declaration declares the object as const. Such an object shall be initialized, and every expression that appears in its initializer (8.5) initialized. If it is initialized by a constructor call, the constructor shall be a constexpr constructor and every argument to the constructor shall be a constant expression. Otherwise, every full-expression that appears in its initializer shall be a constant expression. Every implicit conversion used...



283. Template type-parameters are not syntactically type-names

Section: 9.2.9.3  [dcl.type.simple]     Status: CD1     Submitter: Clark Nelson     Date: 01 May 2001

[Voted into WP at April 2003 meeting.]

Although 13.2 [temp.param] paragraph 3 contains an assertion that

A type-parameter defines its identifier to be a type-name (if declared with class or typename)

the grammar in 9.2.9.3 [dcl.type.simple] paragraph 1 says that a type-name is either a class-name, an enum-name, or a typedef-name. The identifier in a template type-parameter is none of those. One possibility might be to equate the identifier with a typedef-name instead of directly with a type-name, which would have the advantage of not requiring parallel treatment of the two in situations where they are treated the same (e.g., in elaborated-type-specifiers, see issue 245). See also issue 215.

Proposed resolution (Clark Nelson, March 2002):

In 13.2 [temp.param] paragraph 3, change "A type-parameter defines its identifier to be a type-name" to "A type-parameter defines its identifier to be a typedef-name"

In 9.2.9.4 [dcl.type.elab] paragraph 2, change "If the identifier resolves to a typedef-name or a template type-parameter" to "If the identifier resolves to a typedef-name".

This has been consolidated with the edits for some other issues. See N1376=02-0034.




516. Use of signed in bit-field declarations

Section: 9.2.9.3  [dcl.type.simple]     Status: CD1     Submitter: comp.std.c++     Date: 25 Apr 2005

[Voted into WP at the October, 2006 meeting.]

9.2.9.3 [dcl.type.simple] paragraph 3 reads,

It is implementation-defined whether bit-fields and objects of char type are represented as signed or unsigned quantities. The signed specifier forces char objects and bit-fields to be signed; it is redundant with other integral types.

The last sentence in that quote is misleading w.r.t. bit-fields. The first sentence in that quote is correct but incomplete.

Proposed fix: change the two sentences to read:

It is implementation-defined whether objects of char type are represented as signed or unsigned quantities. The signed specifier forces char objects signed; it is redundant with other integral types except when declaring bit-fields (11.4.10 [class.bit]).

Proposed resolution (October, 2005):

Change 9.2.9.3 [dcl.type.simple] paragraph 3 as indicated:

When multiple simple-type-specifiers are allowed, they can be freely intermixed with other decl-specifiers in any order. [Note: It is implementation-defined whether bit-fields and objects of char type and certain bit-fields (11.4.10 [class.bit]) are represented as signed or unsigned quantities. The signed specifier forces bit-fields and char objects and bit-fields to be signed; it is redundant with other integral types in other contexts. end note]



651. Problems in decltype specification and examples

Section: 9.2.9.3  [dcl.type.simple]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 16 Aug 2007

[Voted into the WP at the September, 2008 meeting.]

The second bullet of 9.2.9.3 [dcl.type.simple] paragraph 4 reads,

The reference to “that function” is imprecise; it is not the actual function called at runtime but the statically chosen function (ignoring covariant return types in virtual functions).

Also, the examples in this paragraph have errors:

  1. The declaration of struct A should end with a semicolon.

  2. The lines of the form decltype(...); are ill-formed; they need a declarator.

Proposed Resolution (October, 2007):

Change 9.2.9.3 [dcl.type.simple] paragraph 4 as follows:

The type denoted by decltype(e) is defined as follows:

The operand of the decltype specifier is an unevaluated operand (Clause 7 [expr]).

[Example:

    const int&& foo();
    int i;
    struct A { double x; };
    const A* a = new A();
    decltype(foo()) x1;      // type is const int&&
    decltype(i) x2;          // type is int
    decltype(a->x) x3;       // type is double
    decltype((a->x)) x4;     // type is const double&

end example]




629. auto parsing ambiguity

Section: 9.2.9.6  [dcl.spec.auto]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 14 March 2007

[Voted into the WP at the February, 2008 meeting as paper J16/08-0056 = WG21 N2546.]

We've found an interesting parsing ambiguity with the new meaning of auto. Consider:

    typedef int T;
    void f() {
        auto T = 42;  // Valid or not?
    }

The question here is whether T should be a type specifier or a storage class? 9.2.9.6 [dcl.spec.auto] paragraph 1 says,

The auto type-specifier has two meanings depending on the context of its use. In a decl-specifier-seq that contains at least one type-specifier (in addition to auto) that is not a cv-qualifier, the auto type-specifier specifies that the object named in the declaration has automatic storage duration.

In this case, T is a type-specifier, so the declaration is ill-formed: there is no declarator-id. Many, however, would like to see auto work “just like int,” i.e., forcing T to be redeclared in the inner scope. Concerns cited included hijacking of the name in templates and inline function bodies over the course of time if a program revision introduces a type with that name in the surrounding context. Although it was pointed out that enclosing the name in parentheses in the inner declaration would prevent any such problems, this was viewed as unacceptably ugly.

Notes from the April, 2007 meeting:

The CWG wanted to avoid a rule like, “if auto can be a type-specifier, it is” (similar to the existing “if it can be a declaration, it is” rule) because of the lookahead and backtracking difficulties such an approach would pose for certain kinds of parsing techniques. It was noted that the difficult lookahead cases all involve parentheses, which would not be a problem if only the “=” form of initializer were permitted in auto declarations; only very limited lookahead is required in that case. It was also pointed out that the “if it can be a type-specifier, it is” approach results in a quiet change of meaning for cases like

    typedef int T;
    int n = 3;
    void f() {
        auto T(n);
    }

This currently declares n to be an int variable in the inner scope but would, under the full lookahead approach, declare T to be a variable, quitely changing uses of n inside f() to refer to the outer variable.

The consensus of the CWG was to pursue the change to require the “=” form of initializer for auto.

Notes from the July, 2007 meeting:

See paper J16/07-0197 = WG21 N2337. There was no consensus among the CWG for either of the approaches recommended in the paper; additional input and direction is required.




686. Type declarations/definitions in type-specifier-seqs and type-ids

Section: 9.3.2  [dcl.name]     Status: CD1     Submitter: Jens Maurer     Date: 21 March, 2008

[Voted into the WP at the September, 2008 meeting.]

The restrictions on declaring and/or defining classes inside type-specifier-seqs and type-ids are inconsistent throughout the Standard. This is probably due to the fact that nearly all of the sections that deal with them attempt to state the restriction afresh. There are three cases:

  1. 7.6.2.8 [expr.new], 8.5 [stmt.select], and 11.4.8.3 [class.conv.fct] prohibit “declarations” of classes and enumerations. That means that

        while (struct C* p = 0) ;
    

    is ill-formed unless a prior declaration of C has been seen. These appear to be cases that should have been fixed by issue 379, changing “class declaration” to “class definition,” but were overlooked.

  2. 7.5.5 [expr.prim.lambda], 9.1 [dcl.pre], and 9.3.4.6 [dcl.fct] (late-specified return types) do not contain any restriction at all.

  3. All the remaining cases prohibit “type definitions,” apparently referring to classes and enumerations.

Suggested resolution:

Add something like, “A class or enumeration shall not be defined in a type-specifier-seq or in a type-id,” to a single place in the Standard and remove all other mentions of that restriction (allowing declarations via elaborated-type-specifier).

Mike Miller:

An alias-declaration is just a different syntax for a typedef declaration, which allows definitions of a class in the type; I would expect the same to be true of an alias-declaration. I don't have any particularly strong attachment to allowing a class definition in an alias-declaration. My only concern is introducing an irregularity into what are currently exact-match semantics with typedefs.

There's a parallel restriction in many (but not all?) of these places on typedef declarations.

Jens Maurer:

Those are redundant, as typedef is not a type-specifier, and should be removed as well.

Proposed resolution (March, 2008):

  1. Delete the indicated words from 7.6.1.7 [expr.dynamic.cast] paragraph 1:

  2. ...Types shall not be defined in a dynamic_cast....
  3. Delete the indicated words from 7.6.1.8 [expr.typeid] paragraph 4:

  4. ...Types shall not be defined in the type-id....
  5. Delete the indicated words from 7.6.1.9 [expr.static.cast] paragraph 1:

  6. ...Types shall not be defined in a static_cast....
  7. Delete the indicated words from 7.6.1.10 [expr.reinterpret.cast] paragraph 1:

  8. ...Types shall not be defined in a reinterpret_cast....
  9. Delete the indicated words from 7.6.1.11 [expr.const.cast] paragraph 1:

  10. ...Types shall not be defined in a const_cast....
  11. Delete paragraph 5 of 7.6.2.5 [expr.sizeof]:

  12. Types shall not be defined in a sizeof expression.
  13. Delete paragraph 5 of 7.6.2.8 [expr.new]:

  14. The type-specifier-seq shall not contain class declarations, or enumeration declarations.
  15. Delete paragraph 4 of 7.6.2.6 [expr.alignof]:

  16. A type shall not be defined in an alignof expression.
  17. Delete paragraph 3 of 7.6.3 [expr.cast]:

  18. Types shall not be defined in casts.
  19. Delete the indicated words from 8.5 [stmt.select] paragraph 2:

  20. ...The type-specifier-seq shall not contain typedef and shall not declare a new class or enumeration....
  21. Add the indicated words to 9.2.9 [dcl.type] paragraph 3:

  22. At least one type-specifier that is not a cv-qualifier is required in a declaration unless it declares a constructor, destructor or conversion function. [Footnote: ... ] A type-specifier-seq shall not define a class or enumeration unless it appears in the type-id of an alias-declaration (9.2.4 [dcl.typedef]).
  23. Delete the indicated words from 11.4.8.3 [class.conv.fct] paragraph 1:

  24. ...Classes, enumerations, and typedef-names shall not be declared in the type-specifier-seq....
  25. Delete the indicated words from 14.4 [except.handle] paragraph 1:

  26. ...Types shall not be defined in an exception-declaration.
  27. Delete paragraph 6 of 14.5 [except.spec]:

  28. Types shall not be defined in exception-specifications.

[Drafting note: no changes are required to 7.5.5 [expr.prim.lambda], 9.2.4 [dcl.typedef], 9.12.2 [dcl.align], 9.7.1 [dcl.enum], 9.3.4.6 [dcl.fct], 13.2 [temp.param], or 13.3 [temp.names].]




160. Missing std:: qualification

Section: 9.3.3  [dcl.ambig.res]     Status: CD1     Submitter: Al Stevens     Date: 23 Aug 1999

[Moved to DR at 10/01 meeting.]

9.3.3 [dcl.ambig.res] paragraph 3 shows an example that includes <cstddef> with no using declarations or directives and refers to size_t without the std:: qualification.

Many references to size_t throughout the document omit the std:: namespace qualification.

This is a typical case. The use of std:: is inconsistent throughout the document.

In addition, the use of exception specifications should be examined for consistency.

(See also issue 282.)

Proposed resolution:

In 6.9.1 [intro.execution] paragraph 9, replace all two instances of "sig_atomic_t" by "std::sig_atomic_t".

In 6.2 [basic.def] paragraph 4, replace all three instances of "string" by "std::string" in the example and insert "#include <string>" at the beginning of the example code.

In 6.9.3.1 [basic.start.main] paragraph 4, replace

Calling the function
void exit(int);
declared in <cstdlib>...

by

Calling the function std::exit(int) declared in <cstdlib>...

and also replace "exit" by "std::exit" in the last sentence of that paragraph.

In 6.9.3.1 [basic.start.main] first sentence of paragraph 5, replace "exit" by "std::exit".

In 6.9.3.2 [basic.start.static] paragraph 4, replace "terminate" by "std::terminate".

In 6.9.3.3 [basic.start.dynamic] paragraph 1, replace "exit" by "std::exit" (see also issue 28).

In 6.9.3.3 [basic.start.dynamic] paragraph 3, replace all three instances of "atexit" by "std::atexit" and both instances of "exit" by "std::exit" (see also issue 28).

In 6.9.3.3 [basic.start.dynamic] paragraph 4, replace

Calling the function
void abort();
declared in <cstdlib>...

by

Calling the function std::abort() declared in <cstdlib>...
and "atexit" by "std::atexit" (see also issue 28).

In 6.7.5.5.2 [basic.stc.dynamic.allocation] paragraph 1 third sentence, replace "size_t" by "std::size_t".

In 6.7.5.5.2 [basic.stc.dynamic.allocation] paragraph 3, replace "new_handler" by "std::new_handler". Furthermore, replace "set_new_handler" by "std::set_new_handler" in the note.

In 6.7.5.5.2 [basic.stc.dynamic.allocation] paragraph 4, replace "type_info" by "std::type_info" in the note.

In 6.7.5.5.3 [basic.stc.dynamic.deallocation] paragraph 3, replace all four instances of "size_t" by "std::size_t".

In 6.7.3 [basic.life] paragraph 5, replace "malloc" by "std::malloc" in the example code and insert "#include <cstdlib>" at the beginning of the example code.

In 6.8 [basic.types] paragraph 2, replace "memcpy" by "std::memcpy" (the only instance in the footnote and both instances in the example) and replace "memmove" by "std::memmove" in the footnote (see also issue 43).

In 6.8 [basic.types] paragraph 3, replace "memcpy" by "std::memcpy", once in the normative text and once in the example (see also issue 43).

In 6.8.2 [basic.fundamental] paragraph 8 last sentence, replace "numeric_limits" by "std::numeric_limits".

In 7.6.1.7 [expr.dynamic.cast] paragraph 9 second sentence, replace "bad_cast" by "std::bad_cast".

In 7.6.1.8 [expr.typeid] paragraph 2, replace "type_info" by "std::type_info" and "bad_typeid" by "std::bad_typeid".

In 7.6.1.8 [expr.typeid] paragraph 3, replace "type_info" by "std::type_info".

In 7.6.1.8 [expr.typeid] paragraph 4, replace both instances of "type_info" by "std::type_info".

In 7.6.2.5 [expr.sizeof] paragraph 6, replace both instances of "size_t" by "std::size_t".

In 7.6.2.8 [expr.new] paragraph 11 last sentence, replace "size_t" by "std::size_t".

In 7.6.6 [expr.add] paragraph 6, replace both instances of "ptrdiff_t" by "std::ptrdiff_t".

In 7.6.6 [expr.add] paragraph 8, replace "ptrdiff_t" by "std::ptrdiff_t".

In 8.7 [stmt.jump] paragraph 2, replace "exit" by "std::exit" and "abort" by "std::abort" in the note.

In 9.3.3 [dcl.ambig.res] paragraph 3, replace "size_t" by "std::size_t" in the example.

In 9.5 [dcl.fct.def] paragraph 5, replace "printf" by "std::printf" in the note.

In 11.4.7 [class.dtor] paragraph 13, replace "size_t" by "std::size_t" in the example.

In 11.4.11 [class.free] paragraph 2, replace all four instances of "size_t" by "std::size_t" in the example.

In 11.4.11 [class.free] paragraph 6, replace both instances of "size_t" by "std::size_t" in the example.

In 11.4.11 [class.free] paragraph 7, replace all four instances of "size_t" by "std::size_t" in the two examples.

In 11.9.5 [class.cdtor] paragraph 4, replace "type_info" by "std::type_info".

In 12.5 [over.built] paragraph 13, replace all five instances of "ptrdiff_t" by "std::ptrdiff_t".

In 12.5 [over.built] paragraph 14, replace "ptrdiff_t" by "std::ptrdiff_t".

In 12.5 [over.built] paragraph 21, replace both instances of "ptrdiff_t" by "std::ptrdiff_t".

In 13.3 [temp.names] paragraph 4, replace both instances of "size_t" by "std::size_t" in the example. (The example is quoted in issue 96.)

In 13.4 [temp.arg] paragraph 1, replace "complex" by "std::complex", once in the example code and once in the comment.

In 13.9.4 [temp.expl.spec] paragraph 8, issue 24 has already corrected the example.

In 14.2 [except.throw] paragraph 6, replace "uncaught_exception" by "std::uncaught_exception".

In 14.2 [except.throw] paragraph 7, replace "terminate" by "std::terminate" and both instances of "unexpected" by "std::unexpected".

In 14.2 [except.throw] paragraph 8, replace "terminate" by "std::terminate".

In 14.3 [except.ctor] paragraph 3, replace "terminate" by "std::terminate".

In 14.4 [except.handle] paragraph 9, replace "terminate" by "std::terminate".

In 14.5 [except.spec] paragraph 8, replace "unexpected" by "std::unexpected".

In 14.5 [except.spec] paragraph 9, replace "unexpected" by "std::unexpected" and "terminate" by "std::terminate".

In 14.6 [except.special] paragraph 1, replace "terminate" by "std::terminate" and "unexpected" by "std::unexpected".

In the heading of 14.6.2 [except.terminate], replace "terminate" by "std::terminate".

In 14.6.2 [except.terminate] paragraph 1, footnote in the first bullet, replace "terminate" by "std::terminate". In the same paragraph, fifth bullet, replace "atexit" by "std::atexit". In the same paragraph, last bullet, replace "unexpected_handler" by "std::unexpected_handler".

In 14.6.2 [except.terminate] paragraph 2, replace

In such cases,
void terminate();
is called...

by

In such cases, std::terminate() is called...

and replace all three instances of "terminate" by "std::terminate".

In the heading of _N4606_.15.5.2 [except.unexpected], replace "unexpected" by "std::unexpected".

In _N4606_.15.5.2 [except.unexpected] paragraph 1, replace

...the function
void unexpected();
is called...

by

...the function std::unexpected() is called...
.

In _N4606_.15.5.2 [except.unexpected] paragraph 2, replace "unexpected" by "std::unexpected" and "terminate" by "std::terminate".

In _N4606_.15.5.2 [except.unexpected] paragraph 3, replace "unexpected" by "std::unexpected".

In the heading of 14.6.3 [except.uncaught], replace "uncaught_exception" by "std::uncaught_exception".

In 14.6.3 [except.uncaught] paragraph 1, replace

The function
bool uncaught_exception()
returns true...

by

The function std::uncaught_exception() returns true...
.

In the last sentence of the same paragraph, replace "uncaught_exception" by "std::uncaught_exception".




112. Array types and cv-qualifiers

Section: 9.3.4.5  [dcl.array]     Status: CD1     Submitter: Steve Clamage     Date: 4 May 1999

[Moved to DR at 10/01 meeting.]

Steve Clamage: Section 9.3.4.5 [dcl.array] paragraph 1 reads in part as follows:

Any type of the form "cv-qualifier-seq array of N T" is adjusted to "array of N cv-qualifier-seq T," and similarly for "array of unknown bound of T." [Example:
    typedef int A[5], AA[2][3];
    typedef const A CA;     // type is "array of 5 const int"
    typedef const AA CAA;   // type is "array of 2 array of 3 const int"
end example] [Note: an "array of N cv-qualifier-seq T" has cv-qualified type; such an array has internal linkage unless explicitly declared extern (9.2.9.2 [dcl.type.cv] ) and must be initialized as specified in 9.4 [dcl.init] . ]
The Note appears to contradict the sentence that precedes it.

Mike Miller: I disagree; all it says is that whether the qualification on the element type is direct ("const int x[5]") or indirect ("const A CA"), the array itself is qualified in the same way the elements are.

Steve Clamage: In addition, section 6.8.4 [basic.type.qualifier] paragraph 2 says:

A compound type (6.8.3 [basic.compound] ) is not cv-qualified by the cv-qualifiers (if any) of the types from which it is compounded. Any cv-qualifiers applied to an array type affect the array element type, not the array type (9.3.4.5 [dcl.array] )."
The Note appears to contradict that section as well.

Mike Miller: Yes, but consider the last two sentences of 6.8.4 [basic.type.qualifier] paragraph 5:

Cv-qualifiers applied to an array type attach to the underlying element type, so the notation "cv T," where T is an array type, refers to an array whose elements are so-qualified. Such array types can be said to be more (or less) cv-qualified than other types based on the cv-qualification of the underlying element types.
I think this says essentially the same thing as 9.3.4.5 [dcl.array] paragraph 1 and its note: the qualification of an array is (bidirectionally) equivalent to the qualification of its members.

Mike Ball: I find this a very far reach. The text in 9.3.4.5 [dcl.array] is essentially that which is in the C standard (and is a change from early versions of C++). I don't see any justification at all for the bidirectional equivalence. It seems to me that the note is left over from the earlier version of the language.

Steve Clamage: Finally, the Note seems to say that the declaration

    volatile char greet[6] = "Hello";
gives "greet" internal linkage, which makes no sense.

Have I missed something, or should that Note be entirely removed?

Mike Miller: At least the wording in the note should be repaired not to indicate that volatile-qualification gives an array internal linkage. Also, depending on how the discussion goes, either the wording in 6.8.4 [basic.type.qualifier] paragraph 2 or in paragraph 5 needs to be amended to be consistent regarding whether an array type is considered qualified by the qualification of its element type.

Steve Adamczyk pointed out that the current state of affairs resulted from the need to handle reference binding consistently. The wording is intended to define the question, "Is an array type cv-qualified?" as being equivalent to the question, "Is the element type of the array cv-qualified?"

Proposed resolution (10/00):

Replace the portion of the note in 9.3.4.5 [dcl.array] paragraph 1 reading

such an array has internal linkage unless explicitly declared extern (9.2.9.2 [dcl.type.cv]) and must be initialized as specified in 9.4 [dcl.init].

with

see 6.8.4 [basic.type.qualifier].



140. Agreement of parameter declarations

Section: 9.3.4.6  [dcl.fct]     Status: CD1     Submitter: Steve Clamage     Date: 15 Jul 1999

[Moved to DR at 10/01 meeting.]

9.3.4.6 [dcl.fct] paragraph 3 says,

All declarations for a function with a given parameter list shall agree exactly both in the type of the value returned and in the number and type of parameters.
It is not clear what this requirement means with respect to a pair of declarations like the following:
    int f(const int);
    int f(int x) { ... }
Do they violate this requirement? Is x const in the body of the function declaration?

Tom Plum: I think the FDIS quotation means that the pair of decls are valid. But it doesn't clearly answer whether x is const inside the function definition. As to intent, I know the intent was that if the function definition wants to specify that x is const, the const must appear specifically in the defining decl, not just on some decl elsewhere. But I can't prove that intent from the drafted words.

Mike Miller: I think the intent was something along the following lines:

Two function declarations denote the same entity if the names are the same and the function signatures are the same. (Two function declarations with C language linkage denote the same entity if the names are the same.) All declarations of a given function shall agree exactly both in the type of the value returned and in the number and type of parameters; the presence or absence of the ellipsis is considered part of the signature.
(See 6.6 [basic.link] paragraph 9. That paragraph talks about names in different scopes and says that function references are the same if the "types are identical for purposes of overloading," i.e., the signatures are the same. See also 9.11 [dcl.link] paragraph 6 regarding C language linkage, where only the name is required to be the same for declarations in different namespaces to denote the same function.)

According to this paragraph, the type of a parameter is determined by considering its decl-specifier-seq and declarator and then applying the array-to-pointer and function-to-pointer adjustments. The cv-qualifier and storage class adjustments are performed for the function type but not for the parameter types.

If my interpretation of the intent of the second sentence of the paragraph is correct, the two declarations in the example violate that restriction — the parameter types are not the same, even though the function types are. Since there's no dispensation mentioned for "no diagnostic required," an implementation presumably must issue a diagnostic in this case. (I think "no diagnostic required" should be stated if the declarations occur in different translation units — unless there's a blanket statement to that effect that I have forgotten?)

(I'd also note in passing that, if my interpretation is correct,

    void f(int);
    void f(register int) { }
is also an invalid pair of declarations.)

Proposed resolution (10/00):

  1. In Clause 3 [intro.defs] “signature,” change "the types of its parameters" to "its parameter-type-list (9.3.4.6 [dcl.fct])".

  2. In the third bullet of 6.6 [basic.link] paragraph 9 change "the function types are identical for the purposes of overloading" to "the parameter-type-lists of the functions (9.3.4.6 [dcl.fct]) are identical."

  3. In the sub-bullets of the third bullet of 7.6.1.5 [expr.ref] paragraph 4, change all four occurrences of "function of (parameter type list)" to "function of parameter-type-list."

  4. In 9.3.4.6 [dcl.fct] paragraph 3, change

    All declarations for a function with a given parameter list shall agree exactly both in the type of the value returned and in the number and type of parameters; the presence or absence of the ellipsis is considered part of the function type.
    to
    All declarations for a function shall agree exactly in both the return type and the parameter-type-list.

  5. In 9.3.4.6 [dcl.fct] paragraph 3, change

    The resulting list of transformed parameter types is the function's parameter type list.
    to
    The resulting list of transformed parameter types and the presence or absence of the ellipsis is the function's parameter-type-list.

  6. In 9.3.4.6 [dcl.fct] paragraph 4, change "the parameter type list" to "the parameter-type-list."

  7. In the second bullet of _N4868_.12.2 [over.load] paragraph 2, change all occurrences of "parameter types" to "parameter-type-list."

  8. In 12.2 [over.match] paragraph 1, change "the types of the parameters" to "the parameter-type-list."

  9. In the last sub-bullet of the third bullet of 12.2.2.3 [over.match.oper] paragraph 3, change "parameter type list" to "parameter-type-list."

Note, 7 Sep 2001:

Editorial changes while putting in issue 147 brought up the fact that injected-class-name is not a syntax term and therefore perhaps shouldn't be written with hyphens. The same can be said of parameter-type-list.




262. Default arguments and ellipsis

Section: 9.3.4.6  [dcl.fct]     Status: CD1     Submitter: Jamie Schmeiser     Date: 13 Nov 2000

[Voted into WP at April 2003 meeting.]

The interaction of default arguments and ellipsis is not clearly spelled out in the current wording of the Standard. 9.3.4.7 [dcl.fct.default] paragraph 4 says,

In a given function declaration, all parameters subsequent to a parameter with a default argument shall have default arguments supplied in this or previous declarations.

Strictly speaking, ellipsis isn't a parameter, but this could be clearer. Also, in 9.3.4.6 [dcl.fct] paragraph 2,

If the parameter-declaration-clause terminates with an ellipsis, the number of arguments shall be equal to or greater than the number of parameters specified.

This could be interpreted to refer to the number of arguments after the addition of default arguments to the argument list given in the call expression, but again it could be clearer.

Notes from 04/01 meeting:

The consensus opinion was that an ellipsis is not a parameter and that default arguments should be permitted preceding an ellipsis.

Proposed Resolution (4/02):

Change the following sentence in 9.3.4.6 [dcl.fct] paragraph 2 from

If the parameter-declaration-clause terminates with an ellipsis, the number of arguments shall be equal to or greater than the number of parameters specified.

to

If the parameter-declaration-clause terminates with an ellipsis, the number of arguments shall be equal to or greater than the number of parameters that do not have a default argument.

As noted in the defect, section 9.3.4.7 [dcl.fct.default] is correct but could be clearer.

In 9.3.4.7 [dcl.fct.default], add the following as the first line of the example in paragraph 4.

  void g(int = 0, ...);  // okay, ellipsis is not a parameter so it can follow
                         // a parameter with a default argument



295. cv-qualifiers on function types

Section: 9.3.4.6  [dcl.fct]     Status: CD1     Submitter: Nathan Sidwell     Date: 29 Jun 2001

[Moved to DR at October 2002 meeting.]

This concerns the inconsistent treatment of cv qualifiers on reference types and function types. The problem originated with GCC bug report c++/2810. The bug report is available at http://gcc.gnu.org/cgi-bin/gnatsweb.pl?cmd=view&pr=2810&database=gcc

9.3.4.3 [dcl.ref] describes references. Of interest is the statement (my emphasis)

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef or of a template type argument, in which case the cv-qualifiers are ignored.

Though it is strange to ignore 'volatile' here, that is not the point of this defect report. 9.3.4.6 [dcl.fct] describes function types. Paragraph 4 states,

In fact, if at any time in the determination of a type a cv-qualified function type is formed, the program is ill-formed.

No allowance for typedefs or template type parameters is made here, which is inconsistent with the equivalent reference case.

The GCC bug report was template code which attempted to do,

    template <typename T> void foo (T const &);
    void baz ();
    ...
    foo (baz);

in the instantiation of foo, T is `void ()' and an attempt is made to const qualify that, which is ill-formed. This is a surprise.

Suggested resolution:

Replace the quoted sentence from paragraph 4 in 9.3.4.6 [dcl.fct] with

cv-qualified functions are ill-formed, except when the cv-qualifiers are introduced through the use of a typedef or of a template type argument, in which case the cv-qualifiers are ignored.

Adjust the example following to reflect this.

Proposed resolution (10/01):

In 9.3.4.6 [dcl.fct] paragraph 4, replace

The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type, i.e., it does not create a cv-qualified function type. In fact, if at any time in the determination of a type a cv-qualified function type is formed, the program is ill-formed. [Example:
  typedef void F();
  struct S {
    const F f;          // ill-formed
  };
-- end example]
by
The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. [Example:
  typedef void F();
  struct S {
    const F f;          // ok; equivalent to void f();
  };
-- end example]

Strike the last bulleted item in 13.10.3 [temp.deduct] paragraph 2, which reads

Attempting to create a cv-qualified function type.

Nathan Sidwell comments (18 Dec 2001 ): The proposed resolution simply states attempts to add cv qualification on top of a function type are ignored. There is no mention of whether the function type was introduced via a typedef or template type parameter. This would appear to allow

  void (const *fptr) ();
but, that is not permitted by the grammar. This is inconsistent with the wording of adding cv qualifiers to a reference type, which does mention typedefs and template parameters, even though
  int &const ref;
is also not allowed by the grammar.

Is this difference intentional? It seems needlessly confusing.

Notes from 4/02 meeting:

Yes, the difference is intentional. There is no way to add cv-qualifiers other than those cases.

Notes from April 2003 meeting:

Nathan Sidwell pointed out that some libraries use the inability to add const to a type T as a way of testing that T is a function type. He will get back to us if he has a proposal for a change.




681. Restrictions on declarators with late-specified return types

Section: 9.3.4.6  [dcl.fct]     Status: CD1     Submitter: Mike Miller     Date: 10 March, 2008

[Voted into the WP at the September, 2008 meeting as part of paper N2757.]

The wording added to 9.3.4.6 [dcl.fct] for declarators with late-specified return types says,

In a declaration T D where D has the form

and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T,” T shall be the single type-specifier auto and the derived-declarator-type-list shall be empty.

These restrictions were intended to ensure that the return type of the function is exactly the specified type-id following the ->, not modified by declarator operators and cv-qualification.

Unfortunately, the requirement for an empty derived-declarator-type-list does not achieve this goal but instead forbids declarations like

    auto (*fp)() -> int;    // pointer to function returning int

while allowing declarations like

    auto *f() -> int;       // function returning pointer to int

The reason for this is that, according to the grammar in 9.3 [dcl.decl] paragraph 4, the declarator *f() -> int is parsed as a ptr-operator applied to the direct-declarator f() -> int; that is, the declarator D1 seen in 9.3.4.6 [dcl.fct] is just f, and the derived-declarator-type-list is thus empty.

By contrast, the declarator (*fp)() -> int is parsed as the direct-declarator (*fp) followed by the parameter-declaration-clause, etc. In this case, D1 in 9.3.4.6 [dcl.fct] is (*fp) and the derived-declarator-type-list is “pointer to,” i.e., not empty.

My personal view is that there is no reason to forbid the (*fp)() -> int form, and that doing so is problematic. For example, this restriction would require users desiring the late-specified return type syntax to write function parameters as function types and rely on parameter type transformations rather than writing them as pointer-to-function types, as they will actually turn out to be:

    void f(auto (*fp)() -> int);  // ill-formed
    void f(auto fp() -> int);     // OK (but icky)

It may be helpful in deciding whether to allow this form to consider the example of a function returning a pointer to a function. With the current restriction, only one of the three plausible forms is allowed:

    auto (*f())() -> int;           // Disallowed
    auto f() -> int (*)();          // Allowed
    auto f() -> auto (*)() -> int;  // Disallowed
Suggested resolution:
  1. Delete the words “and the derived-declarator-type-list shall be empty” from 9.3.4.6 [dcl.fct] paragraph 2.

  2. Add a new paragraph following 9.3 [dcl.decl] paragraph 4:

  3. A ptr-operator shall not be applied, directly or indirectly, to a function declarator with a late-specified return type (9.3.4.6 [dcl.fct]).

Proposed resolution (June, 2008):

  1. Change the grammar in 9.3 [dcl.decl] paragraph 4 as follows:

  2. Change the grammar in 9.3.2 [dcl.name] paragraph 1 as follows:

  3. Change 9.3.4.6 [dcl.fct] paragraph 2 as follows:

  4. ... T shall be the single type-specifier auto and the derived-declarator-type-list shall be empty. Then the type...
  5. Change all occurrences of direct-new-declarator in 7.6.2.8 [expr.new] to noptr-new-declarator. These changes appear in the grammar in paragraph 1 and in the text of paragraphs 6-8, as follows:

  6. When the allocated object is an array (that is, the direct-noptr-new-declarator syntax is used or the new-type-id or type-id denotes an array type), the new-expression yields a pointer to the initial element (if any) of the array. [Note: both new int and new int[10] have type int* and the type of new int[i][10] is int (*)[10]end note]

    Every constant-expression in a direct-noptr-new-declarator shall be an integral constant expression (7.7 [expr.const]) and evaluate to a strictly positive value. The expression in a direct-noptr-new-declarator shall be of integral type, enumeration type, or a class type for which a single non-explicit conversion function to integral or enumeration type exists (11.4.8 [class.conv]). If the expression is of class type, the expression is converted by calling that conversion function, and the result of the conversion is used in place of the original expression. If the value of the expression is negative, the behavior is undefined. [Example: given the definition int n = 42, new float[n][5] is well-formed (because n is the expression of a direct-noptr-new-declarator), but new float[5][n] is ill-formed (because n is not a constant expression). If n is negative, the effect of new float[n][5] is undefined. —end example]

    When the value of the expression in a direct-noptr-new-declarator is zero, the allocation function is called to allocate an array with no elements.




136. Default arguments and friend declarations

Section: 9.3.4.7  [dcl.fct.default]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 9 July 1999

[Moved to DR at 10/01 meeting.]

9.3.4.7 [dcl.fct.default] paragraph 4 says,

For non-template functions, default arguments can be added in later declarations of a function in the same scope. Declarations in different scopes have completely distinct sets of default arguments. That is, declarations in inner scopes do not acquire default arguments from declarations in outer scopes, and vice versa.
It is unclear how this wording applies to friend function declarations. For example,
    void f(int, int, int=0);             // #1
    class C {
        friend void f(int, int=0, int);  // #2
    };
    void f(int=0, int, int);             // #3
Does the declaration at #2 acquire the default argument from #1, and does the one at #3 acquire the default arguments from #2?

There are several related questions involved with this issue:

  1. Is the friend declaration in the scope of class C or in the surrounding namespace scope?

    Mike Miller: 9.3.4.7 [dcl.fct.default] paragraph 4 is speaking about the lexical location of the declaration... The friend declaration occurs in a different declarative region from the declaration at #1, so I would read [this paragraph] as saying that it starts out with a clean slate of default arguments.

    Bill Gibbons: Yes. It occurs in a different region, although it declares a name in the same region (i.e. a redeclaration). This is the same as with local externs and is intended to work the same way. We decided that local extern declarations cannot add (beyond the enclosing block) new default arguments, and the same should apply to friend declarations.

    John Spicer: The question is whether [this paragraph] does (or should) mean declarations that appear in the same lexical scope or declarations that declare names in the same scope. In my opinion, it really needs to be the latter. It seems somewhat paradoxical to say that a friend declaration declares a function in namespace scope yet the declaration in the class still has its own attributes. To make that work I think you'd have to make friends more like block externs that really do introduce a name into the scope in which the declaration is contained.

  2. Should default arguments be permitted in friend function declarations, and what effect should they have?

    Bill Gibbons: In the absence of a declaration visible in class scope to which they could be attached, default arguments on friend declarations do not make sense. [They should be] ill-formed, to prevent surprises.

    John Spicer: It is important that the following case work correctly:

            class X {
                    friend void f(X x, int i = 1){}
            };
    
            int main()
            {
                    X x;
                    f(x);
            }
    

    In other words, a function first declared in a friend declaration must be permitted to have default arguments and those default arguments must be usable when the function is found by argument dependent lookup. The reason that this is important is that it is common practice to define functions in friend declarations in templates, and that definition is the only place where the default arguments can be specified.

  3. What restrictions should be placed on default argument usage with friend declarations?

    John Spicer: We want to avoid instantiation side effects. IMO, the way to do this would be to prohibit a friend declaration from providing default arguments if a declaration of that function is already visible. Once a function has had a default specified in a friend declaration it should not be possible to add defaults in another declaration be it a friend or normal declaration.

    Mike Miller: The position that seems most reasonable to me is to allow default arguments in friend declarations to be used in Koenig lookup, but to say that they are completely unrelated to default arguments in declarations in the surrounding scope; and to forbid use of a default argument in a call if more than one declaration in the overload set has such a default, as in the proposed resolution for issue 1.

(See also issues 21, 95, 138, 139, 143, 165, and 166.)

Notes from 10/99 meeting:

Four possible outcomes were identified:

  1. If a friend declaration declares a default parameter, allow no other declarations of that function in the translation unit.
  2. Same as preceding, but only allow the friend declaration if it is also a definition.
  3. Disallow default arguments in friend declarations.
  4. Treat the default arguments in each friend declaration as a distinct set, causing an error if the call would be ambiguous.

The core group eliminated the first and fourth options from consideration, but split fairly evenly between the remaining two.

A straw poll of the full committee yielded the following results (given as number favoring/could live with/"over my dead body"):

  1. 0/14/5
  2. 8/13/5
  3. 11/7/14
  4. 7/10/9

Additional discussion is recorded in the "Record of Discussion" for the meeting, J16/99-0036 = WG21 N1212. See also paper J16/00-0040 = WG21 N1263.

Proposed resolution (10/00):

In 9.3.4.7 [dcl.fct.default], add following paragraph 4:

If a friend declaration specifies a default argument expression, that declaration must be a definition and shall be the only declaration of the function or function template in the translation unit.



5. CV-qualifiers and type conversions

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Josee Lajoie     Date: unknown

[Moved to DR at 4/01 meeting.]

The description of copy-initialization in 9.4 [dcl.init] paragraph 14 says:

Should "destination type" in this last bullet refer to "cv-unqualified destination type" to make it clear that the destination type excludes any cv-qualifiers? This would make it clearer that the following example is well-formed:
     struct A {
       A(A&);
     };
     struct B : A { };

     struct C {
       operator B&();
     };

     C c;
     const A a = c; // allowed?

The temporary created with the conversion function is an lvalue of type B. If the temporary must have the cv-qualifiers of the destination type (i.e. const) then the copy-constructor for A cannot be called to create the object of type A from the lvalue of type const B. If the temporary has the cv-qualifiers of the result type of the conversion function, then the copy-constructor for A can be called to create the object of type A from the lvalue of type const B. This last outcome seems more appropriate.

Steve Adamczyk:

Because of late changes to this area, the relevant text is now the third sub-bullet of the fourth bullet of 9.4 [dcl.init] paragraph 14:

Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated... The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the destination type. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization.

The issue still remains whether the wording should refer to "the cv-unqualified version of the destination type." I think it should.

Notes from 10/00 meeting:

The original example does not illustrate the remaining problem. The following example does:

    struct C { };
    C c;
    struct A {
        A(const A&);
        A(const C&);
    };
    const volatile A a = c;    // Okay

Proposed Resolution (04/01):

In 9.4 [dcl.init], paragraph 14, bullet 4, sub-bullet 3, change

if the function is a constructor, the call initializes a temporary of the destination type.

to

if the function is a constructor, the call initializes a temporary of the cv-unqualified version of the destination type.



78. Section 8.5 paragraph 9 should state it only applies to non-static objects

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Judy Ward     Date: 15 Dec 1998

Paragraph 9 of 9.4 [dcl.init] says:

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for an object, the object and its subobjects, if any, have an indeterminate initial value; if the object or any of its subobjects are of const-qualified type, the program is ill-formed.
It should be made clear that this paragraph does not apply to static objects.

Proposed resolution (10/00): In 9.4 [dcl.init] paragraph 9, replace

Otherwise, if no initializer is specified for an object..."
with
Otherwise, if no initializer is specified for a non-static object...



177. Lvalues vs rvalues in copy-initialization

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Steve Adamczyk     Date: 25 October 1999

[Moved to DR at 4/02 meeting.]

Is the temporary created during copy-initialization of a class object treated as an lvalue or an rvalue? That is, is the following example well-formed or not?

    struct B { };
    struct A {
        A(A&);    // not const
        A(const B&);
    };
    B b;
    A a = b;

According to 9.4 [dcl.init] paragraph 14, the initialization of a is performed in two steps. First, a temporary of type A is created using A::A(const B&). Second, the resulting temporary is used to direct-initialize a using A::A(A&).

The second step requires binding a reference to non-const to the temporary resulting from the first step. However, 9.4.4 [dcl.init.ref] paragraph 5 requires that such a reference be bound only to lvalues.

It is not clear from 7.2.1 [basic.lval] whether the temporary created in the process of copy-initialization should be treated as an lvalue or an rvalue. If it is an lvalue, the example is well-formed, otherwise it is ill-formed.

Proposed resolution (04/01):

  1. In 9.4 [dcl.init] paragraph 14, insert the following after "the call initializes a temporary of the destination type":

    The temporary is an rvalue.
  2. In 14.2 [except.throw] paragraph 3, replace

    The temporary is used to initialize the variable...

    with

    The temporary is an lvalue and is used to initialize the variable...

(See also issue 84.)




277. Zero-initialization of pointers

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Andrew Sawyer     Date: 5 Apr 2001

[Moved to DR at 10/01 meeting.]

The intent of 9.4 [dcl.init] paragraph 5 is that pointers that are zero-initialized will contain a null pointer value. Unfortunately, the wording used,

...set to the value of 0 (zero) converted to T

does not match the requirements for creating a null pointer value given in 7.3.12 [conv.ptr] paragraph 1:

A null pointer constant is an integral constant expression (7.7 [expr.const]) rvalue of integer type that evaluates to zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type...

The problem is that the "value of 0" in the description of zero-initialization is not specified to be an integral constant expression. Nonconstant expressions can also have the value 0, and converting a nonconst 0 to pointer type need not result in a null pointer value.

Proposed resolution (04/01):

In 9.4 [dcl.init] paragraph 5, change

...set to the value 0 (zero) converted to T;

to

...set to the value 0 (zero), taken as an integral constant expression, converted to T; [footnote: as specified in 7.3.12 [conv.ptr], converting an integral constant expression whose value is 0 to a pointer type results in a null pointer value.]



302. Value-initialization and generation of default constructor

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Steve Adamczyk     Date: 23 Jul 2001

[Moved to DR at October 2002 meeting.]

We've been looking at implementing value-initialization. At one point, some years back, I remember Bjarne saying that something like X() in an expression should produce an X object with the same value one would get if one created a static X object, i.e., the uninitialized members would be zero-initialized because the whole object is initialized at program startup, before the constructor is called.

The formulation for default-initialization that made it into TC1 (in 9.4 [dcl.init]) is written a little differently (see issue 178), but I had always assumed that it would still be a valid implementation to zero the whole object and then call the default constructor for the troublesome "non-POD but no user-written constructor" cases.

That almost works correctly, but I found a problem case:

    struct A {
      A();
      ~A();
    };
    struct B {
      // B is a non-POD with no user-written constructor.
      // It has a nontrivial generated constructor.
      const int i;
      A a;
    };
    int main () {
      // Value-initializing a "B" doesn't call the default constructor for
      // "B"; it value-initializes the members of B.  Therefore it shouldn't
      // cause an error on generation of the default constructor for the
      // following:
      new B();
    }

If the definition of the B::B() constructor is generated, an error is issued because the const member "i" is not initialized. But the definition of value-initialization doesn't require calling the constructor, and therefore it doesn't require generating it, and therefore the error shouldn't be detected.

So this is a case where zero-initializing and then calling the constructor is not equivalent to value-initializing, because one case generates an error and the other doesn't.

This is sort of unfortunate, because one doesn't want to generate all the required initializations at the point where the "()" initialization occurs. One would like those initializations to be packaged in a function, and the default constructor is pretty much the function one wants.

I see several implementation choices:

  1. Zero the object, then call the default generated constructor. This is not valid unless the standard is changed to say that the default constructor might be generated for value-initialization cases like the above (that is, it's implementation-dependent whether the constructor definition is generated). The zeroing operation can of course be optimized, if necessary, to hit only the pieces of the object that would otherwise be left uninitialized. An alternative would be to require generation of the constructor for value-initialization cases, even if the implementation technique doesn't call the constructor at that point. It's pretty likely that the constructor is going to have to be generated at some point in the program anyway.
  2. Make a new value-initialization "constructor," whose body looks a lot like the usual generated constructor, but which also zeroes other members. No errors would be generated while generating this modified constructor, because it generates code that does full initialization. (Actually, it wouldn't guarantee initialization of reference members, and that might be an argument for generating the constructor, in order to get that error.) This is standard-conforming, but it destroys object-code compatibility.
  3. Variation on (1): Zero first, and generate the object code for the default constructor when it's needed for value-initialization cases, but don't issue any errors at that time. Issue the errors only if it turns out the constructor is "really" referenced. Aside from the essential shadiness of this approach, I fear that something in the generation of the constructor will cause a template instantiation which will be an abservable side effect.

Personally, I find option 1 the least objectionable.

Proposed resolution (10/01):

Add the indicated wording to the third-to-last sentence of 6.3 [basic.def.odr] pararaph 2:

A default constructor for a class is used by default initialization or value initialization as specified in 9.4 [dcl.init].

Add a footnote to the indicated bullet in 9.4 [dcl.init] paragraph 5:

Add the indicated wording to the first sentence of 11.4.5 [class.ctor] paragraph 7:

An implicitly-declared default constructor for a class is implicitly defined when it is used (6.3 [basic.def.odr]) to create an object of its class type (6.7.2 [intro.object]).



509. Dead code in the specification of default initialization

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Mike Miller     Date: 18 Mar 2005

[Voted into the WP at the September, 2008 meeting (resolution in paper N2762).]

The definition of default initialization (9.4 [dcl.init] paragraph 5) is:

However, default initialization is invoked only for non-POD class types and arrays thereof (7.6.2.8 [expr.new] paragraph 15 for new-expressions, 9.4 [dcl.init] paragraph 10 for top-level objects, and 11.9.3 [class.base.init] paragraph 4 for member and base class subobjects — but see issue 510). Consequently, all cases that invoke default initialization are handled by the first two bullets; the third bullet can never be reached. Its presence is misleading, so it should be removed.

Notes from the September, 2008 meeting:

The approach adopted in the resolution in paper N2762 was different from the suggestion above: it changes the definition of default initialization to include POD types and changes the third bullet to specify that “no initialization is performed.”




543. Value initialization and default constructors

Section: 9.4  [dcl.init]     Status: CD1     Submitter: Mike Miller     Date: 27 October 2005

[Voted into the WP at the September, 2008 meeting (resolution in paper N2762).]

The wording resulting from the resolution of issue 302 does not quite implement the intent of the issue. The revised wording of 6.3 [basic.def.odr] paragraph 2 is:

A default constructor for a class is used by default initialization or value initialization as specified in 9.4 [dcl.init].

This sounds as if 9.4 [dcl.init] specifies how and under what circumstances value initialization uses a default constructor (which was, in fact, the case for default initialization in the original wording). However, the normative text there makes it plain that value initialization does not call the default constructor (the permission granted to implementations to call the default constructor for value initialization is in a non-normative footnote).

The example that occasioned this observation raises an additional question. Consider:

    struct POD {
      const int x;
    };

    POD data = POD();

According to the (revised) resolution of issue 302, this code is ill-formed because the implicitly-declared default constructor will be implicitly defined as a result of being used by value initialization (11.4.5 [class.ctor] paragraph 7), and the implicitly-defined constructor fails to initialize a const-qualified member (11.9.3 [class.base.init] paragraph 4). This seems unfortunate, because the (trivial) default constructor of a POD class is otherwise not used — default initialization applies only to non-PODs — and it is not actually needed in value initialization. Perhaps value initialization should be defined to “use” the default constructor only for non-POD classes? If so, both of these problems would be resolved by rewording the above-referenced sentence of 6.3 [basic.def.odr] paragraph 2 as:

A default constructor for a non-POD class is used by default initialization or value initialization as specified in (9.4 [dcl.init]).

Notes from the April, 2006 meeting:

The approach favored by the CWG was to leave 6.3 [basic.def.odr] unchanged and to add normative wording to 9.4 [dcl.init] indicating that it is unspecified whether the default constructor is called.

Notes from the October, 2006 meeting:

The CWG now prefers that it should not be left unspecified whether programs of this sort are well- or ill-formed; instead, the Standard should require that the default constructor be defined in such cases. Three possibilities of implementing this decision were discussed:

  1. Change 6.3 [basic.def.odr] to state flatly that the default constructor is used by value initialization (removing the implication that 9.4 [dcl.init] determines the conditions under which it is used).

  2. Change 9.4 [dcl.init] to specify that non-union class objects with no user-declared constructor are value-initialized by first zero-initializing the object and then calling the (implicitly-defined) default constructor, replacing the current specification of value-initializing each of its sub-objects.

  3. Add a normative statement to 9.4 [dcl.init] that value-initialization causes the implicitly-declared default constructor to be implicitly defined, even if it is not called.

Proposed resolution (June, 2008):

Change the second bullet of the value-initialization definition in 9.4 [dcl.init] paragraph 5 as follows:

Notes from the September, 2008 meeting:

The resolution supplied in paper N2762 differs from the June, 2008 proposed resolution in that the implicitly-declared default constructor is only called (and thus defined) if it is non-trivial, making the struct POD example above well-formed.




430. Ordering of expression evaluation in initializer list

Section: 9.4.2  [dcl.init.aggr]     Status: CD1     Submitter: Nathan Sidwell     Date: 23 July 2003

[Voted into the WP at the April, 2007 meeting as part of paper J16/07-0099 = WG21 N2239.]

A recent GCC bug report ( http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11633) asks about the validity of

  int count = 23;
  int foo[] = { count++, count++, count++ };
is this undefined or unspecified or something else? I can find nothing in 9.4.2 [dcl.init.aggr] that indicates whether the components of an initializer-list are evaluated in order or not, or whether they have sequence points between them.

6.7.8/23 of the C99 std has this to say

The order in which any side effects occur among the initialization list expressions is unspecified.
I think similar wording is needed in 9.4.2 [dcl.init.aggr]

Steve Adamczyk: I believe the standard is clear that each initializer expression in the above is a full-expression (6.9.1 [intro.execution]/12-13; see also issue 392) and therefore there is a sequence point after each expression (6.9.1 [intro.execution]/16). I agree that the standard does not seem to dictate the order in which the expressions are evaluated, and perhaps it should. Does anyone know of a compiler that would not evaluate the expressions left to right?

Mike Simons: Actually there is one, that does not do left to right: gcc/C++. None of the post increment operations take effect until after the statement finishes. So in the sample code gcc stores 23 into all positions in the array. The commercial vendor C++ compilers for AIX, Solaris, Tru64, HPUX (parisc and ia64), and Windows, all do sequence points at each ',' in the initializer list.




491. Initializers for empty-class aggregrate members

Section: 9.4.2  [dcl.init.aggr]     Status: CD1     Submitter: Nathan Sidwell     Date: 15 Dec 2004

[Voted into WP at April, 2007 meeting.]

The current wording of 9.4.2 [dcl.init.aggr] paragraph 8 requires that

An initializer for an aggregate member that is an empty class shall have the form of an empty initializer-list {}.

This is overly constraining. There is no reason that the following should be ill-formed:

    struct S { };
    S s;
    S arr[1] = { s };

Mike Miller: The wording of 9.4.2 [dcl.init.aggr] paragraph 8 is unclear. “An aggregate member” would most naturally mean “a member of an aggregate.” In context, however, I think it must mean “a member [of an aggregate] that is an aggregate”, that is, a subaggregate. Members of aggregates need not themselves be aggregates (cf paragraph 13 and 11.9.2 [class.expl.init]); it cannot be the case that an object of an empty class with a user-declared constructor must be initialized with {} when it is a member of an aggregate. This wording should be clarified, regardless of the decision on Nathan's point.

Proposed resolution (October, 2005):

This issue is resolved by the resolution of issue 413.




632. Brace-enclosed initializer for scalar member of aggregate

Section: 9.4.2  [dcl.init.aggr]     Status: CD1     Submitter: Greg Comeau     Date: 3 May 2007

[Voted into the WP at the June, 2008 meeting as part of paper N2672.]

C (both C90 and C99) appear to allow a declaration of the form

    struct S { int i; } s = { { 5 } };

in which the initializer of a scalar member of an aggregate can itself be brace-enclosed. The relevant wording from the C99 Standard is found in 6.7.8 paragraph 11:

The initializer for a scalar shall be a single expression, optionally enclosed in braces.

and paragraph 16:

Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed list of initializers for the elements or named members.

The “list of initializers” in paragraph 16 must be a recursive reference to paragraph 11 (that's the only place that describes how an initialized item gets its value from the initializer expression), which would thus make the “brace-enclosed” part of paragraph 11 apply to each of the initializers in the list in paragraph 16 as well.

This appears to be an incompatibility between C and C++: 9.4.2 [dcl.init.aggr] paragraph 11 says,

If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the members of a subaggregate....

which clearly leaves the impression that only a subaggregate may be initialized by a brace-enclosed initializer-clause.

Either the specification in 9.4.2 [dcl.init.aggr] should be changed to allow a brace-enclosed initializer of a scalar member of an aggregate, as in C, or this incompatibility should be listed in Appendix Clause Annex C [diff].

Notes from the July, 2007 meeting:

It was noted that implementations differ in their handling of this construct; however, the issue is long-standing and fairly obscure.

Notes from the October, 2007 meeting:

The initializer-list proposal will resolve this issue when it is adopted.




291. Overload resolution needed when binding reference to class rvalue

Section: 9.4.4  [dcl.init.ref]     Status: CD1     Submitter: Andrei Iltchenko     Date: 15 Jun 2001

[Voted into WP at October 2005 meeting.]

There is a place in the Standard where overload resolution is implied but the way that a set of candidate functions is to be formed is omitted. See below.

According to the Standard, when initializing a reference to a non-volatile const class type (cv1 T1) with an rvalue expression (cv2 T2) where cv1 T1 is reference compatible with cv2 T2, the implementation shall proceed in one of the following ways (except when initializing the implicit object parameter of a copy constructor) 9.4.4 [dcl.init.ref] bullet 5.2 sub-bullet 1:

While the first case is quite obvious, the second one is a bit unclear as it says "a constructor is called to copy the entire rvalue object into the temporary" without specifying how the temporary is created -- by direct-initialization or by copy-initialization? As stated in DR 152, this can make a difference when the copy constructor is declared as explicit. How should the set of candidate functions be formed? The most appropriate guess is that it shall proceed as per 12.2.2.4 [over.match.ctor].

Another detail worth of note is that in the draft version of the Standard as of 2 December 1996 the second bullet read:

J. Stephen Adamczyk replied that the reason for changing "a copy constructor" to "a constructor" was to allow for member template converting constructors.

However, the new wording is somewhat in conflict with the footnote #93 that says that when initializing the implicit object parameter of a copy constructor an implementation must eventually choose the first alternative (binding without copying) to avoid infinite recursion. This seems to suggest that a copy constructor is always used for initializing the temporary of type "cv1 T2".

Furthermore, now that the set of candidate functions is not limited to only the copy constructors of T2, there might be some unpleasant consequences. Consider a rather contrived sample below:

    int   * pi = ::new(std::nothrow) int;
    const std::auto_ptr<int>   & ri = std::auto_ptr<int>(pi);

In this example the initialization of the temporary of type '<TT>const std::auto_ptr<int>' (to which 'ri' is meant to be subsequently bound) doesn't fail, as it would had the approach with copy constructors been retained, instead, a yet another temporary gets created as the well-known sequence:

    std::auto_ptr<int>::operator std::auto_ptr_ref<int>()
    std::auto_ptr<int>(std::auto_ptr_ref<int>)

is called (assuming, of course, that the set of candidate functions is formed as per 12.2.2.4 [over.match.ctor]). The second temporary is transient and gets destroyed at the end of the initialization. I doubt that this is the way that the committee wanted this kind of reference binding to go.

Besides, even if the approach restricting the set of candidates to copy constructors is restored, it is still not clear how the initialization of the temporary (to which the reference is intended to be bound) is to be performed -- using direct-initialization or copy-initialization.

Another place in the Standard that would benefit from a similar clarification is the creation of an exception object, which is delineated in 14.2 [except.throw].

David Abrahams (February 2004): It appears, looking at core 291, that there may be a need to tighten up 9.4.4 [dcl.init.ref]/5.

Please see the attached example file, which demonstrates "move semantics" in C++98. Many compilers fail to compile test 10 because of the way 8.5.3/5 is interpreted. My problem with that interpretation is that test 20:

    typedef X const XC;
    sink2(XC(X()));
does compile. In other words, it *is* possible to construct the const temporary from the rvalue. IMO, that is the proper test.

8.5.3/5 doesn't demand that a "copy constructor" is used to copy the temporary, only that a constructor is used "to copy the temporary". I hope that when the language is tightened up to specify direct (or copy initialization), that it also unambiguously allows the enclosed test to compile. Not only is it, I believe, within the scope of reasonable interpretation of the current standard, but it's an incredibly important piece of functionality for library writers and users alike.

#include <iostream>
#include <cassert>

template <class T, class X>
struct enable_if_same
{
};

template <class X>
struct enable_if_same<X, X>
{
    typedef char type;
};

struct X
{
    static int cnt;  // count the number of Xs

    X()
      : id(++cnt)
      , owner(true)
    {
        std::cout << "X() #" << id << std::endl;
    }

    // non-const lvalue - copy ctor
    X(X& rhs)
      : id(++cnt)
      , owner(true)
    {
        std::cout << "copy #" << id << " <- #" << rhs.id << std::endl;
    }

    // const lvalue - T will be deduced as X const
    template <class T>
    X(T& rhs, typename enable_if_same<X const,T>::type = 0)
      : id(++cnt)
      , owner(true)
    {
        std::cout << "copy #" << id << " <- #" << rhs.id << " (const)" << std::endl;
    }

    ~X()
    {
        std::cout << "destroy #" << id << (owner?"":" (EMPTY)") << std::endl;
    }

 private:    // Move stuff
    struct ref { ref(X*p) : p(p) {} X* p; };

 public:    // Move stuff
    operator ref() {
        return ref(this);
    }

    // non-const rvalue
    X(ref rhs)
      : id(++cnt)
      , owner(rhs.p->owner)
    {
        std::cout << "MOVE #" << id << " <== #" << rhs.p->id << std::endl;
        rhs.p->owner = false;
        assert(owner);
    }

 private:   // Data members
    int id;
    bool owner;
};

int X::cnt;


X source()
{
    return X();
}

X const csource()
{
    return X();
}

void sink(X)
{
    std::cout << "in rvalue sink" << std::endl;
}

void sink2(X&)
{
    std::cout << "in non-const lvalue sink2" << std::endl;
}

void sink2(X const&)
{
    std::cout << "in const lvalue sink2" << std::endl;
}

void sink3(X&)
{
    std::cout << "in non-const lvalue sink3" << std::endl;
}

template <class T>
void tsink(T)
{
    std::cout << "in templated rvalue sink" << std::endl;
}

int main()
{
    std::cout << " ------ test 1, direct init from rvalue ------- " << std::endl;
#ifdef __GNUC__ // GCC having trouble parsing the extra parens
    X z2((0, X() ));
#else
    X z2((X()));
#endif

    std::cout << " ------ test 2, copy init from rvalue ------- " << std::endl;
    X z4 = X();

    std::cout << " ------ test 3, copy init from lvalue ------- " << std::endl;
    X z5 = z4;

    std::cout << " ------ test 4, direct init from lvalue ------- " << std::endl;
    X z6(z4);

    std::cout << " ------ test 5, construct const ------- " << std::endl;
    X const z7;

    std::cout << " ------ test 6, copy init from lvalue ------- " << std::endl;
    X z8 = z7;

    std::cout << " ------ test 7, direct init from lvalue ------- " << std::endl;
    X z9(z7);

    std::cout << " ------ test 8, pass rvalue by-value ------- " << std::endl;
    sink(source());

    std::cout << " ------ test 9, pass const rvalue by-value ------- " << std::endl;
    sink(csource());

    std::cout << " ------ test 10, pass rvalue by overloaded reference ------- " << std::endl;
    // This one fails in Comeau's strict mode due to 8.5.3/5.  GCC 3.3.1 passes it.
    sink2(source());

    std::cout << " ------ test 11, pass const rvalue by overloaded reference ------- " << std::endl;
    sink2(csource());

#if 0    // These two correctly fail to compile, just as desired
    std::cout << " ------ test 12, pass rvalue by non-const reference ------- " << std::endl;
    sink3(source());

    std::cout << " ------ test 13, pass const rvalue by non-const reference ------- " << std::endl;
    sink3(csource());
#endif

    std::cout << " ------ test 14, pass lvalue by-value ------- " << std::endl;
    sink(z5);

    std::cout << " ------ test 15, pass const lvalue by-value ------- " << std::endl;
    sink(z7);

    std::cout << " ------ test 16, pass lvalue by-reference ------- " << std::endl;
    sink2(z4);

    std::cout << " ------ test 17, pass const lvalue by const reference ------- " << std::endl;
    sink2(z7);

    std::cout << " ------ test 18, pass const lvalue by-reference ------- " << std::endl;
#if 0   // correctly fails to compile, just as desired
    sink3(z7);
#endif

    std::cout << " ------ test 19, pass rvalue by value to template param ------- " << std::endl;
    tsink(source());

    std::cout << " ------ test 20, direct initialize a const A with an A ------- " << std::endl;
    typedef X const XC;
    sink2(XC(X()));
}

Proposed Resolution:

(As proposed by N1610 section 5, with editing.)

Change 8.5.3 [stmt.switch] paragraph 5, second bullet, first sub-bullet, second sub-sub-bullet as follows:

A temporary of type "cv1 T2" [sic] is created, and a constructor is called to copy the entire rvalue object into the temporary via copy-initialization from the entire rvalue object. The reference is bound to the temporary or to a sub-object within the temporary.

The text immediately following that is changed as follows:

The constructor that would be used to make the copy shall be callable whether or not the copy is actually done. The constructor and any conversion function that would be used in the initialization shall be callable whether or not the temporary is actually created.

Note, however, that the way the core working group is leaning on issue 391 (i.e., requiring direct binding) would make this change unnecessary.

Proposed resolution (April, 2005):

This issue is resolved by the resolution of issue 391.




391. Require direct binding of short-lived references to rvalues

Section: 9.4.4  [dcl.init.ref]     Status: CD1     Submitter: Raoul Gough     Date: 14 Nov 2002

[Voted into WP at October 2005 meeting.]

After some email exchanges with Rani Sharoni, I've come up with the following proposal to allow reference binding to non-copyable rvalues in some cases. Rationale and some background appear afterwards.

---- proposal ----

Replace the section of 9.4.4 [dcl.init.ref] paragraph 5 that begins "If the initializer expression is an rvalue" with the following:

---- rationale ----

  1. The intention of the current wording is to provide the implementation freedom to construct an rvalue of class type at an arbitrary location and copy it zero or more times before binding any reference to it.
  2. The standard allows code to call a member function on an rvalue of class type (in 7.6.1.5 [expr.ref], I guess). This means that the implementation can be forced to bind the reference directly, with no freedom to create any temporary copies. e.g.
       class nc {
         nc (nc const &);  // private, nowhere defined
       public:
         nc ();
         nc const &by_ref () const { return *this; }
       };
    
       void f () {
         void g (nc const &);
    
         g (nc());          // Ill-formed
         g (nc().by_ref()); // Ok - binds directly to rvalue
       }
    
    Forcing a direct binding in this way is possible wherever the lifetime of the reference does not extend beyond the containing full expression, since the reference returned by the member function remains valid for this long.
  3. As demonstrated above, existing implementations must already be capable of constructing an rvalue of class type in the "right" place the first time. Some compilers already silently allow the direct binding of references to non-copyable rvalues.
  4. The change will not break any portable user code. It would break any platform-specific user code that relies on copies being performed by the particular implementation.

---- background ----

The proposal is based on a recent discussion in this group. I originally wanted to leave the implementation free to copy the rvalue if there was a callable copy constructor, and only have to bind directly if none was callable. Unfortunately, a traditional compiler can't always tell whether a function is callable or not, e.g. if the copy constructor is declared but not defined. Rani pointed this out in an example, and suggested that maybe trivial copy constructors should still be allowed (by extension, maybe wherever the compiler can determine callability). I've gone with this version because it's simpler, and I also figure the "as if" rule gives the compiler some freedom with POD types anyway.

Notes from April 2003 meeting:

We agreed generally with the proposal. We were unsure about the need for the restriction regarding long-lived references. We will check with the proposer about that.

Jason Merrill points out that the test case in issue 86 may be a case where we do not want to require direct binding.

Further information from Rani Sharoni (April 2003):

I wasn't aware about the latest suggestion of Raoul as it appears in core issue 391. In our discussions we tried to formulate a different proposal.

The rational, as we understood, behind the implementation freedom to make an extra copying (8.5.3/5/2/12) of the rvalue is to allow return values in registers which on some architectures are not addressable. The example that Raoul and I presented shows that this implementation freedom is not always possible since we can "force" the rvalue to be addressable using additional member function (by_ref). The example only works for short lived rvalues and this is probably why Raoul narrow the suggestion.

I had different rational which was related to the implementation of conditional operator in VC. It seems that when conditional operator is involved VC does use an extra copying when the lifetime of the temporary is extended:

  struct A { /* ctor with side effect */};

  void f(A& x) {
    A const& r = cond ? A(1) : x; // VC actually make an extra copy of
                                  // the rvalue A(1)
  }

I don't know what the consideration behind the VC implementation was (I saw open bug on this issue) but it convinced me to narrow the suggestion.

IMHO such limitation seems to be too strict because it might limit the optimizer since returning class rvalues in registers might be useful (although I'm not aware about any implementation that actually does it). My suggestion was to forbid the extra copying if the ctor is not viable (e.g. A::A(A&) ). In this case the implementation "freedom" doesn't exist (since the code might not compile) and only limits the programmer freedom (e.g. Move Constructors - http://www.cuj.com/experts/2102/alexandr.htm [Note: URL is now defunct; observed March,2019.]).

Core issue 291 is strongly related to the above issue and I personally prefer to see it resolved first. It seems that VC already supports the resolution I prefer.

Notes from October 2003 meeting:

We ended up feeling that this is just one of a number of cases of optimizations that are widely done by compilers and allowed but not required by the standard. We don't see any strong reason to require compilers to do this particular optimization.

Notes from the March 2004 meeting:

After discussing issue 450, we found ourselves reconsidering this, and we are now inclined to make a change to require the direct binding in all cases, with no restriction on long-lived references. Note that such a change would eliminate the need for a change for issue 291.

Proposed resolution (October, 2004):

Change 9.4.4 [dcl.init.ref] bullet 5.2 sub-bullet 1 as follows:

If the initializer expression is an rvalue, with T2 a class type, and "cv1 T1" is reference-compatible with "cv2 T2", the reference is bound to the object represented by the rvalue (see 7.2.1 [basic.lval]) or to a sub-object within that object. in one of the following ways (the choice is implementation-defined): The constructor that would be used to make the copy shall be callable whether or not the copy is actually done. [Example:
  struct A { };
  struct B : public A { } b;
  extern B f();
  const A& rca = f ();  // Bound Either bound to the A sub-object of the B rvalue,
                        // or the entire B object is copied and the reference
                        // is bound to the A sub-object of the copy
end example]

[This resolution also resolves issue 291.]




450. Binding a reference to const to a cv-qualified array rvalue

Section: 9.4.4  [dcl.init.ref]     Status: CD1     Submitter: Steve Adamczyk     Date: 16 Jan 2004

[Voted into WP at October 2005 meeting.]

It's unclear whether the following is valid:

const int N = 10;
const int M = 20;
typedef int T;
void f(T const (&x)[N][M]){}

struct X {
	int i[10][20];
};

X g();

int main()
{
	f(g().i);
}

When you run this through 9.4.4 [dcl.init.ref], you sort of end up falling off the end of the standard's description of reference binding. The standard says in the final bullet of paragraph 5 that an array temporary should be created and copy-initialized from the rvalue array, which seems implausible.

I'm not sure what the right answer is. I think I'd be happy with allowing the binding in this case. We would have to introduce a special case like the one for class rvalues.

Notes from the March 2004 meeting:

g++ and EDG give an error. Microsoft (8.0 beta) and Sun accept the example. Our preference is to allow the direct binding (no copy). See the similar issue with class rvalues in issue 391.

Proposed resolution (October, 2004):

  1. Insert a new bullet in 9.4.4 [dcl.init.ref] bullet 5.2 before sub-bullet 2 (which begins, “Otherwise, a temporary of type ‘cv1 T1’ is created...”):

    If the initializer expression is an rvalue, with T2 an array type, and “cv1 T1” is reference-compatible with “cv2 T2”, the reference is bound to the object represented by the rvalue (see 7.2.1 [basic.lval]).
  2. Change 7.2.1 [basic.lval] paragraph 2 as follows:

    An lvalue refers to an object or function. Some rvalue expressions — those of (possibly cv-qualified) class or array type or cv-qualified class type — also refer to objects.



172. Unsigned int as underlying type of enum

Section: 9.7.1  [dcl.enum]     Status: CD1     Submitter: Bjarne Stroustrup     Date: 26 Sep 1999

[Moved to DR at October 2002 meeting.]

According to 9.7.1 [dcl.enum] paragraph 5, the underlying type of an enum is an unspecified integral type, which could potentially be unsigned int. The promotion rules in 7.3.7 [conv.prom] paragraph 2 say that such an enumeration value used in an expression will be promoted to unsigned int. This means that a conforming implementation could give the value false for the following code:

    enum { zero };
    -1 < zero;       // might be false
This is counterintuitive. Perhaps the description of the underlying type of an enumeration should say that an unsigned underlying type can be used only if the values of the enumerators cannot be represented in the corresponding signed type. This approach would be consistent with the treatment of integral promotion of bitfields (7.3.7 [conv.prom] paragraph 3) .

On a related note, 9.7.1 [dcl.enum] paragraph 5 says,

the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.

This specification does not allow for an enumeration like

    enum { a = -1, b = UINT_MAX };

Since each enumerator can fit in an int or unsigned int, the underlying type is required to be no larger than int, even though there is no such type that can represent all the enumerators.

Proposed resolution (04/01; obsolete, see below):

Change 9.7.1 [dcl.enum] paragraph 5 as follows:

It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int neither int nor unsigned int can represent all the enumerator values. Furthermore, the underlying type shall not be an unsigned type if the corresponding signed type can represent all the enumerator values.

See also issue 58.

Notes from 04/01 meeting:

It was noted that 7.3.7 [conv.prom] promotes unsigned types smaller than int to (signed) int. The signedness chosen by an implementation for small underlying types is therefore unobservable, so the last sentence of the proposed resolution above should apply only to int and larger types. This observation also prompted discussion of an alternative approach to resolving the issue, in which the bmin and bmax of the enumeration would determine the promoted type rather than the underlying type.

Proposed resolution (10/01):

Change 7.3.7 [conv.prom] paragraph 2 from

An rvalue of type wchar_t (6.8.2 [basic.fundamental]) or an enumeration type (9.7.1 [dcl.enum]) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, or unsigned long.
to
An rvalue of type wchar_t (6.8.2 [basic.fundamental]) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, or unsigned long. An rvalue of an enumeration type (9.7.1 [dcl.enum]) can be converted to an rvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range bmin to bmax as described in 9.7.1 [dcl.enum]): int, unsigned int, long, or unsigned long.




377. Enum whose enumerators will not fit in any integral type

Section: 9.7.1  [dcl.enum]     Status: CD1     Submitter: Mark Mitchell     Date: 30 August 2002

[Voted into WP at April 2003 meeting.]

9.7.1 [dcl.enum] defines the underlying type of an enumeration as an integral type "that can represent all the enumerator values defined in the enumeration".

What does the standard say about this code:

  enum E { a = LONG_MIN, b = ULONG_MAX };

?

I think this should be ill-formed.

Proposed resolution:

In 9.7.1 [dcl.enum] paragraph 5 after

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration.
insert
If no integral type can represent all the enumerator values, the enumeration is ill-formed.




518. Trailing comma following enumerator-list

Section: 9.7.1  [dcl.enum]     Status: CD1     Submitter: Charles Bryant     Date: 10 May 2005

[Voted into WP at April, 2006 meeting.]

The C language (since C99), and some C++ compilers, accept:

    enum { FOO, };

as syntactically valid. It would be useful

This proposed change is to permit a trailing comma in enum by adding:

enum identifieropt { enumerator-list , }

as an alternative definition for the enum-specifier nonterminal in 9.7.1 [dcl.enum] paragraph 1.

Proposed resolution (October, 2005):

Change the grammar in 9.7.1 [dcl.enum] paragraph 1 as indicated:

enum-specifier:



660. Unnamed scoped enumerations

Section: 9.7.1  [dcl.enum]     Status: CD1     Submitter: Daveed Vandevoorde     Date: 15 November 2007

[Voted into the WP at the September, 2008 meeting.]

The current specification of scoped enumerations does not appear to forbid an example like the following, even though the enumerator e cannot be used:

    enum class { e };

This might be covered by 9.1 [dcl.pre] paragraph 3,

In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (Clause 11 [class]) or enumeration (9.7.1 [dcl.enum]), that is, when the decl-specifier-seq contains either a class-specifier, an elaborated-type-specifier with a class-key (11.3 [class.name]), or an enum-specifier. In these cases and whenever a class-specifier or enum-specifier is present in the decl-specifier-seq, the identifiers in these specifiers are among the names being declared by the declaration (as class-names, enum-names, or enumerators, depending on the syntax). In such cases, and except for the declaration of an unnamed bit-field (11.4.10 [class.bit]), the decl-specifier-seq shall introduce one or more names into the program, or shall redeclare a name introduced by a previous declaration.

which, when combined with paragraph 2,

A declaration occurs in a scope (6.4 [basic.scope]); the scope rules are summarized in 6.5 [basic.lookup]. A declaration that declares a function or defines a class, namespace, template, or function also has one or more scopes nested within it. These nested scopes, in turn, can have declarations nested within them. Unless otherwise stated, utterances in Clause 9 [dcl.dcl] about components in, of, or contained by a declaration or subcomponent thereof refer only to those components of the declaration that are not nested within scopes nested within the declaration.

appears to rule out the similar class definition,

    struct { int m; };

However, a scoped enumeration is not listed in paragraph 2 among the constructs containing a nested scope (although 6.4.7 [basic.scope.enum] does describe “enumeration scope”); furthermore, an enumerator-definition is not formally a “nested declaration.” If unusable scoped enumeration definitions are to be banned, these shortcomings in 9.1 [dcl.pre] paragraph 2 must be addressed. (A note in 9.7.1 [dcl.enum] mentioning that unnamed scoped enumerations are not allowed would also be helpful.)

Notes from the February, 2008 meeting:

The consensus was to require that the identifier be present in an enum-specifier unless the enum-key is enum.

Proposed resolution (June, 2008):

Change 9.7.1 [dcl.enum] paragraph 2 as follows:

...The enum-keys enum class and enum struct are semantically equivalent; an enumeration type declared with one of these is a scoped enumeration, and its enumerators are scoped enumerators. The optional identifier shall not be omitted in the declaration of a scoped enumeration. The type-specifier-seq of an enum-base...



540. Propagation of cv-qualifiers in reference-to-reference collapse

Section: 9.8.2  [namespace.def]     Status: CD1     Submitter: Russell Yanofsky     Date: 24 September 2005

[Voted into the WP at the October, 2006 meeting as part of paper J16/06-0188 = WG21 N2118.]

The resolution of issue 106 specifies that an attempt to create a type “reference to cv1 T,” where T is a typedef or template parameter of the type “reference to cv2 S,” actually creates the type “reference to cv12 S,” where cv12 is the union of the two sets of cv-qualifiers.

One objection that has been raised to this resolution is that it is inconsistent with the treatment of cv-qualification and references specified in 9.3.4.3 [dcl.ref] paragraph 1, which says that cv-qualifiers applied to a typedef or template argument that is a reference type are ignored. For example:

    typedef int& intref;
    const intref r1;       // reference to int
    const intref& r2;      // reference to const int

In fact, however, these two declarations are quite different. In the declaration of r1, const applies to a “top-level” reference, while in the declaration of t2, it occurs under a reference. In general, cv-qualifiers that appear under a reference are preserved, even if the type appears in a context in which top-level cv-qualification is removed, for example, in determining the type of a function from parameter types (9.3.4.6 [dcl.fct] paragraph 3) and in template argument deduction (13.10.3.2 [temp.deduct.call] paragraph 2).

Another objection to the resolution is that type composition gives different results in a single declaration than it does when separated into two declarations. For example:

    template <class T>
    struct X {
       typedef T const T_const;
       typedef T_const& type1;
       typedef T const& type2;
    };

    X<int&>::type1 t1;    // int&
    X<int&>::type2 t2;    // int const&

The initial motivation for the propagation of cv-qualification during reference-to-reference collapse was to prevent inadvertent loss of cv-qualifiers in contexts in which it could make a difference. For example, if the resolution were changed to discard, rather than propagate, embedded cv-qualification, overload resolution could surprisingly select a non-const version of a member function:

   struct X {
       void g();
       void g() const;
   };

   template <typename T> struct S {
       static void f(const T& t) {
           t.g();    // const or non-const???
       }
   };

   X x;

   void q() {
       S<X>::f(x);    // calls X::g() const
       S<X&>::f(x);   // calls X::g()
   }

Another potentially-surprising outcome of dropping embedded cv-qualifiers would be:

   template <typename T> struct A {
       void f(T&);          // mutating version
       void f(const T&);    // non-mutating version
   };

   A<int&> ai;    // Ill-formed: A<int&> declares f(int&) twice

On the other hand, those who would like to see the resolution changed to discard embedded cv-qualifiers observe that these examples are too simple to be representative of real-world code. In general, it is unrealistic to expect that a template written with non-reference type parameters in mind will automatically work correctly with reference type parameters as a result of applying the issue 106 resolution. Instead, template metaprogramming allows the template author to choose explicitly whether cv-qualifiers are propagated or dropped, according to the intended use of the template, and it is more important to respect the reasonable intuition that a declaration involving a template parameter will not change the type that the parameter represents.

As a sample of real-world code, tr1::tuple was examined. In both cases — the current resolution of issue 106 and one in which embedded cv-qualifiers were dropped — some metaprogramming was required to implement the intended interface, although the version reflecting the revised resolution was somewhat simpler.

Notes from the October, 2005 meeting:

The consensus of the CWG was that the resolution of issue 106 should be revised not to propagate embedded cv-qualification.

Note (February, 2006):

The wording included in the rvalue-reference paper, J16/06-0022 = WG21 N1952, incorporates changes intended to implement the October, 2005 consensus of the CWG.




11. How do the keywords typename/template interact with using-declarations?

Section: 9.9  [namespace.udecl]     Status: CD1     Submitter: Bill Gibbons     Date: unknown

[Voted into WP at March 2004 meeting.]

Issue 1:

The working paper is not clear about how the typename/template keywords interact with using-declarations:

     template<class T> struct A {
         typedef int X;
     };

     template<class T> void f() {
         typename A<T>::X a;      // OK
         using typename A<T>::X;  // OK
         typename X b;  // ill-formed; X must be qualified
         X c;  // is this OK?
     }
When the rules for typename and the similar use of template were decided, we chose to require that they be used at every reference. The way to avoid typename at every use is to declare a typedef; then the typedef name itself is known to be a type. For using-declarations, we decided that they do not introduce new declarations but rather are aliases for existing declarations, like symbolic links. This makes it unclear whether the declaration "X c;" above should be well-formed, because there is no new name declared so there is no declaration with a "this is a type" attribute. (The same problem would occur with the template keyword when a member template of a dependent class is used). I think these are the main options:
  1. Continue to allow typename in using-declarations, and template (for member templates) too. Attach the "is a type" or "is a template" attribute to the placeholder name which the using-declaration "declares"
  2. Disallow typename and template in using-declarations (just as class-keys are disallowed now). Allow typename and template before unqualified names which refer to dependent qualified names through using-declarations.
  3. Document that this is broken.
Suggested Resolution:

The core WG already resolved this issue according to (1), but the wording does not seem to have been added to the standard. New wording needs to be drafted.

Issue 2:

Either way, one more point needs clarification. If the first option is adopted:

     template<class T> struct A {
         struct X { };
     };

     template<class T> void g() {
         using typename A<T>::X;
         X c;    // if this is OK, then X by itself is a  type
         int X;  // is this OK?
     }
When "g" is instantiated, the two declarations of X are compatible (9.9 [namespace.udecl] paragraph 10) . But there is no way to know this when the definition of "g" is compiled. I think this case should be ill-formed under the first option. (It cannot happen under the second option.) If the second option is adopted:
     template<class T> struct A {
         struct X { };
     };

     template<class T> void g() {
         using A<T>::X;
         int X;  // is this OK?
     }
Again, the instantiation would work but there is no way to know that in the template definition. I think this case should be ill-formed under the second option. (It would already be ill-formed under the first option.)

From John Spicer:

The "not a new declaration" decision is more of a guiding principle than a hard and fast rule. For example, a name introduced in a using-declaration can have different access than the original declaration.

Like symbolic links, a using-declaration can be viewed as a declaration that declares an alias to another name, much like a typedef.

In my opinion, "X c;" is already well-formed. Why would we permit typename to be used in a using-declaration if not to permit this precise usage?

In my opinion, all that needs to be done is to clarify that the "typeness" or "templateness" attribute of the name referenced in the using-declaration is attached to the alias created by the using-declaration. This is solution #1.

Tentative Resolution:

The rules for multiple declarations with the same name in the same scope should treat a using-declaration which names a type as a typedef, just as a typedef of a class name is treated as a class declaration. This needs drafting work. Also see Core issue 36.

Rationale (04/99): Any semantics associated with the typename keyword in using-declarations should be considered an extension.

Notes from the April 2003 meeting:

This was reopened because we are now considering extensions again. We agreed that it is desirable for the typename to be "sticky" on a using-declaration, i.e., references to the name introduced by the using-declaration are known to be type names without the use of the typename keyword (which can't be specified on an unqualified name anyway, as of now). The related issue with the template keyword already has a separate issue 109.

Issue 2 deals with the "struct hack." There is an example in 9.9 [namespace.udecl] paragraph 10 that shows a use of using-declarations to import two names that coexist because of the "struct hack." After some deliberation, we decided that the template-dependent using-declaration case is different enough that we did not have to support the "struct hack" in that case. A name introduced in such a case is like a typedef, and no other hidden type can be accessed through an elaborated type specifier.

Proposed resolution (April 2003, revised October 2003):

Add a new paragraph to the bottom of 9.9 [namespace.udecl]:

If a using-declaration uses the keyword typename and specifies a dependent name (13.8.3 [temp.dep]), the name introduced by the using-declaration is treated as a typedef-name (9.2.4 [dcl.typedef]).



258. using-declarations and cv-qualifiers

Section: 9.9  [namespace.udecl]     Status: CD1     Submitter: Liam Fitzpatrick     Date: 2 Nov 2000

[Voted into WP at April 2003 meeting.]

According to 9.9 [namespace.udecl] paragraph 12,

When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).

Note that this description says nothing about the cv-qualification of the hiding and hidden member functions. This means, for instance, that a non-const member function in the derived class hides a const member function with the same name and parameter types instead of overloading it in the derived class scope. For example,

    struct A {
      virtual int f() const;
      virtual int f();
    };
    struct B: A {
      B();
      int f();
      using A::f;
    };

    const B cb;
    int i = cb.f(); // ill-formed: A::f() const hidden in B

The same terminology is used in 11.7.3 [class.virtual] paragraph 2:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

Notes on the 04/01 meeting:

The hiding and overriding should be on the basis of the function signature, which includes any cv-qualification on the function.

Proposed resolution (04/02):

In 9.9 [namespace.udecl] paragraph 12 change:

When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).
to read:
When a using-declaration brings names from a base class into a derived class scope, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list (9.3.4.6 [dcl.fct]), and cv-qualification in a base class (rather than conflicting).

In 11.7.3 [class.virtual] paragraph 2 change:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
to read:
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (9.3.4.6 [dcl.fct]), and cv-qualification as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

See issue 140 for the definition of parameter-type-list.




460. Can a using-declaration name a namespace?

Section: 9.9  [namespace.udecl]     Status: CD1     Submitter: John Spicer     Date: 12 Feb 2004

[Voted into WP at April 2005 meeting.]

Can a using-declaration be used to import a namespace?

namespace my_namespace{
  namespace my_namespace2 {
    int function_of_my_name_space(){ return 2;}
  }
}

int main (){
  using  ::my_namespace::my_namespace2;
  return my_namespace2::function_of_my_name_space();
}

Several popular compilers give an error on this, but there doesn't seem to be anything in 9.9 [namespace.udecl] that prohibits it. It should be noted that the user can get the same effect by using a namespace alias:

  namespace my_namespace2 = ::my_namespace::my_namespace2;

Notes from the March 2004 meeting:

We agree that it should be an error.

Proposed resolution (October, 2004):

Add the following as a new paragraph after 9.9 [namespace.udecl] paragraph 5:

A using-declaration shall not name a namespace;



4. Does extern "C" affect the linkage of function names with internal linkage?

Section: 9.11  [dcl.link]     Status: CD1     Submitter: Mike Anderson     Date: unknown

[Moved to DR at 4/01 meeting.]

9.11 [dcl.link] paragraph 6 says the following:

Does this apply to static functions as well? For example, is the following well-formed?
        extern "C" {
            static void f(int) {}
            static void f(float) {}
        };
Can a function with internal linkage "have C linkage" at all (assuming that phrase means "has extern "C" linkage"), for how can a function be extern "C" if it's not extern? The function type can have extern "C" linkage — but I think that's independent of the linkage of the function name. It should be perfectly reasonable to say, in the example above, that extern "C" applies only to the types of f(int) and f(float), not to the function names, and that the rule in 9.11 [dcl.link] paragraph 6 doesn't apply.

Suggested resolution: The extern "C" linkage specification applies only to the type of functions with internal linkage, and therefore some of the rules that have to do with name overloading don't apply.

Proposed Resolution:

The intent is to distingush implicit linkage from explicit linkage for both name linkage and language (function type) linkage. (It might be more clear to use the terms name linkage and type linkage to distinguish these concepts. A function can have a name with one kind of linkage and a type with a different kind of linkage. The function itself has no linkage: it has no name, only the declaration has a name. This becomes more obvious when you consider function pointers.)

The tentatively agreed proposal is to apply implicit linkage to names declared in brace-enclosed linkage specifications and to non-top-level names declared in simple linkage specifications; and to apply explicit linkage to top-level names declared in simple linkage specifications.

The language linkage of any function type formed through a function declarator is that of the nearest enclosing linkage-specification. For purposes of determining whether the declaration of a namespace-scope name matches a previous declaration, the language linkage portion of the type of a function declaration (that is, the language linkage of the function itself, not its parameters, return type or exception specification) is ignored.

For a linkage-specification using braces, i.e.

extern string-literal { declaration-seqopt }
the linkage of any declaration of a namespace-scope name (including local externs) which is not contained in a nested linkage-specification, is not declared to have no linkage (static), and does not match a previous declaration is given the linkage specified in the string-literal. The language linkage of the type of any function declaration of a namespace-scope name (including local externs) which is not contained in a nested linkage-specification and which is declared with function declarator syntax is the same as that of a matching previous declaration, if any, else is specified by string-literal.

For a linkage-specification without braces, i.e.

extern string-literal declaration

the linkage of the names declared in the top-level declarators of declaration is specified by string-literal; if this conflicts with the linkage of any matching previous declarations, the program is ill-formed. The language linkage of the type of any top-level function declarator is specified by string-literal; if this conflicts with the language linkage of the type of any matching previous function declarations, the program is ill-formed. The effect of the linkage-specification on other (non top-level) names declared in declaration is the same as that of the brace-enclosed form.

Bill Gibbons: In particular, these should be well-formed:

    extern "C" void f(void (*fp)());   // parameter type is pointer to
                                       // function with C language linkage
    extern "C++" void g(void (*fp)()); // parameter type is pointer to
                                       // function with C++ language linkage

    extern "C++" {                     // well-formed: the linkage of "f"
        void f(void(*fp)());           // and the function type used in the
    }                                  // parameter still "C"

    extern "C" {                       // well-formed: the linkage of "g"
        void g(void(*fp)());           // and the function type used in the
    }                                  // parameter still "C++"

but these should not:

    extern "C++" void f(void(*fp)());  // error - linkage of "f" does not
                                       // match previous declaration
                                       // (linkage of function type used in
                                       // parameter is still "C" and is not
                                       // by itself ill-formed)
    extern "C" void g(void(*fp)());    // error - linkage of "g" does not
                                       // match previous declaration
                                       // (linkage of function type used in
                                       // parameter is still "C++" and is not
                                       // by itself ill-formed)

That is, non-top-level declarators get their linkage from matching declarations, if any, else from the nearest enclosing linkage specification. (As already described, top-level declarators in a brace-enclosed linkage specification get the linkage from matching declarations, if any, else from the linkage specifcation; while top-level declarators in direct linkage specifications get their linkage from that specification.)

Mike Miller: This is a pretty significant change from the current specification, which treats the two forms of language linkage similarly for most purposes. I don't understand why it's desirable to expand the differences.

It seems very unintuitive to me that you could have a top-level declaration in an extern "C" block that would not receive "C" linkage.

In the current standard, the statement in 9.11 [dcl.link] paragraph 4 that

the specified language linkage applies to the function types of all function declarators, function names, and variable names introduced by the declaration(s)

applies to both forms. I would thus expect that in

    extern "C" void f(void(*)());
    extern "C++" {
        void f(void(*)());
    }
    extern "C++" f(void(*)());

both "C++" declarations would be well-formed, declaring an overloaded version of f that takes a pointer to a "C++" function as a parameter. I wouldn't expect that either declaration would be a redeclaration (valid or invalid) of the "C" version of f.

Bill Gibbons: The potential difficulty is the matching process and the handling of deliberate overloading based on language linkage. In the above examples, how are these two declarations matched:

    extern "C" void f(void (*fp1)());

    extern "C++" {
        void f(void(*fp2)());
    }

given that the linkage that is part of fp1 is "C" while the linkage (prior to the matching process) that is part of fp2 is "C++"?

The proposal is that the linkage which is part of the parameter type is not determined until after the match is attempted. This almost always correct because you can't overload "C" and "C++" functions; so if the function names match, it is likely that the declarations are supposed to be the same.

Mike Miller: This seems like more trouble than it's worth. This comparison of function types ignoring linkage specifications is, as far as I know, not found anywhere in the current standard. Why do we need to invent it?

Bill Gibbons: It is possible to construct pathological cases where this fails, e.g.

    extern "C" typedef void (*PFC)();  // pointer to "C" linkage function
    void f(PFC);         // parameter is pointer to "C" function
    void f(void (*)());  // matching declaration or overload based on
                         // difference in linkage type?

It is reasonable to require explicit typedefs in this case so that in the above example the second function declaration gets its parameter type function linkage from the first function declaration.

(In fact, I think you can't get into this situation without having already used typedefs to declare different language linkage for the top-level and parameter linkages.)

For example, if the intent is to overload based on linkage a typedef is needed:

    extern "C" typedef void (*PFC)();  // pointer to "C" linkage function
    void f(PFC);              // parameter is pointer to "C" function
    typedef void (*PFCPP)();  // pointer to "C++" linkage function
    void f(PFCPP);            // parameter is pointer to "C++" function

In this case the two function declarations refer to different functions.

Mike Miller: This seems pretty strange to me. I think it would be simpler to determine the type of the parameter based on the containing linkage specification (implicitly "C++") and require a typedef if the user wants to override the default behavior. For example:

    extern "C" {
        typedef void (*PFC)();    // pointer to "C" function
        void f(void(*)());        // takes pointer to "C" function
    }

    void f(void(*)());            // new overload of "f", taking
                                  // pointer to "C++" function

    void f(PFC);                  // redeclare extern "C" version

Notes from 04/00 meeting:

The following changes were tentatively approved, but because they do not completely implement the proposal above the issue is being kept for the moment in "drafting" status.

Notes from 10/00 meeting:

After further discussion, the core language working group determined that the more extensive proposal described above is not needed and that the following changes are sufficient.

Proposed resolution (04/01):

  1. Change the first sentence of 9.11 [dcl.link] paragraph 1 from

    All function types, function names, and variable names have a language linkage.

    to

    All function types, function names with external linkage, and variable names with external linkage have a language linkage.
  2. Change the following sentence of 9.11 [dcl.link] paragraph 4:
    In a linkage-specification, the specified language linkage applies to the function types of all function declarators, function names, and variable names introduced by the declaration(s).

    to

    In a linkage-specification, the specified language linkage applies to the function types of all function declarators, function names with external linkage, and variable names with external linkage declared within the linkage-specification.
  3. Add at the end of the final example on 9.11 [dcl.link] paragraph 4:

        extern "C" {
          static void f4();    // the name of the function f4 has
                               // internal linkage (not C language
                               // linkage) and the function's type
                               // has C language linkage
        }
        extern "C" void f5() {
          extern void f4();    // Okay -- name linkage (internal)
                               // and function type linkage (C
                               // language linkage) gotten from
                               // previous declaration.
        }
        extern void f4();      // Okay -- name linkage (internal)
                               // and function type linkage (C
                               // language linkage) gotten from
                               // previous declaration.
        void f6() {
          extern void f4();    // Okay -- name linkage (internal)
                               // and function type linkage (C
                               // language linkage) gotten from
                               // previous declaration.
        }
    
  4. Change 9.11 [dcl.link] paragraph 7 from

    Except for functions with internal linkage, a function first declared in a linkage-specification behaves as a function with external linkage. [Example:

        extern "C" double f();
        static double f();     // error
    

    is ill-formed (9.2.2 [dcl.stc]). ] The form of linkage-specification that contains a braced-enclosed declaration-seq does not affect whether the contained declarations are definitions or not (6.2 [basic.def]); the form of linkage-specification directly containing a single declaration is treated as an extern specifier (9.2.2 [dcl.stc]) for the purpose of determining whether the contained declaration is a definition. [Example:

        extern "C" int i;      // declaration
        extern "C" {
    	  int i;           // definition
        }
    

    end example] A linkage-specification directly containing a single declaration shall not specify a storage class. [Example:

        extern "C" static void f(); // error
    

    end example]

    to

    A declaration directly contained in a linkage-specification is treated as if it contains the extern specifier (9.2.2 [dcl.stc]) for the purpose of determining the linkage of the declared name and whether it is a definition. Such a declaration shall not specify a storage class. [Example:
        extern "C" double f();
        static double f();     // error
        extern "C" int i;      // declaration
        extern "C" {
    	    int i;         // definition
        }
        extern "C" static void g(); // error
    

    end example]




29. Linkage of locally declared functions

Section: 9.11  [dcl.link]     Status: CD1     Submitter: Mike Ball     Date: 19 Mar 1998

[Moved to DR at October 2002 meeting. This was incorrectly marked as having DR status between 4/01 and 4/02. It was overlooked when issue 4 was moved to DR at the 4/01 meeting; this one should have been moved as well, because it's resolved by the changes there.]

Consider the following:

    extern "C" void foo()
    {
        extern void bar();
        bar();
    }
Does "bar()" have "C" language linkage?

The ARM is explicit and says

A linkage-specification for a function also applies to functions and objects declared within it.
The DIS says
In a linkage-specification, the specified language linkage applies to the function types of all function declarators, function names, and variable names introduced by the declaration(s).
Is the body of a function definition part of the declaration?

From Mike Miller:

Yes: from 9.1 [dcl.pre] paragraph 1,

and 9.5 [dcl.fct.def] paragraph 1: At least that's how I'd read it.

From Dag Brück:

Consider the following where extern "C" has been moved to a separate declaration:

    extern "C" void foo();

    void foo() { extern void bar(); bar(); }
I think the ARM wording could possibly be interpreted such that bar() has "C" linkage in my example, but not the DIS wording.

As a side note, I have always wanted to think that placing extern "C" on a function definition or a separate declaration would produce identical programs.

Proposed Resolution (04/01):

See the proposed resolution for Core issue 4, which covers this case.

The ODR should also be checked to see whether it addresses name and type linkage.




175. Class name injection and base name access

Section: Clause 11  [class]     Status: CD1     Submitter: John Spicer     Date: 21 February 1999

[Moved to DR at 10/01 meeting.]

With class name injection, when a base class name is used in a derived class, the name found is the injected name in the base class, not the name of the class in the scope containing the base class. Consequently, if the base class name is not accessible (e.g., because is is in a private base class), the base class name cannot be used unless a qualified name is used to name the class in the class or namespace of which it is a member.

Without class name injection the following example is valid. With class name injection, A is inaccessible in class C.

    class A { };
    class B: private A { };
    class C: public B {
        A* p;    // error: A inaccessible
    };

At the least, the standard should be more explicit that this is, in fact, ill-formed.

(See paper J16/99-0010 = WG21 N1187.)

Proposed resolution (04/01):

Add to the end of 11.8.2 [class.access.spec] paragraph 3:

[Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared.] [Example:

    class A { };
    class B : private A { };
    class C : public B {
        A* p;    // error: injected-class-name A is inaccessible
        ::A* q;  // OK
    };

end example]




273. POD classes and operator&()

Section: Clause 11  [class]     Status: CD1     Submitter: Andrei Iltchenko     Date: 10 Mar 2001

[Moved to DR at October 2002 meeting.]

I think that the definition of a POD class in the current version of the Standard is overly permissive in that it allows for POD classes for which a user-defined operator function operator& may be defined. Given that the idea behind POD classes was to achieve compatibility with C structs and unions, this makes 'Plain old' structs and unions behave not quite as one would expect them to.

In the C language, if x and y are variables of struct or union type S that has a member m, the following expression are allowed: &x, x.m, x = y. While the C++ standard guarantees that if x and y are objects of a POD class type S, the expressions x.m, x = y will have the same effect as they would in C, it is still possible for the expression &x to be interpreted differently, subject to the programmer supplying an appropriate version of a user-defined operator function operator& either as a member function or as a non-member function.

This may result in surprising effects. Consider:

    // POD_bomb is a POD-struct. It has no non-static non-public data members,
    // no virtual functions, no base classes, no constructors, no user-defined
    // destructor, no user-defined copy assignment operator, no non-static data
    // members of type pointer to member, reference, non-POD-struct, or
    // non-POD-union.
    struct  POD_bomb  {
       int   m_value1;
       int   m_value2;
       int  operator&()
       {   return  m_value1++;   }
       int  operator&() const
       {   return  m_value1 + m_value2;   }
    };

6.8 [basic.types] paragraph 2 states:

For any complete POD object type T, whether or not the object holds a valid value of type T, the underlying bytes (6.7.1 [intro.memory]) making up the object can be copied into an array of char or unsigned char [footnote: By using, for example, the library functions (16.4.2.3 [headers]) memcpy or memmove]. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value. [Example:
    #define N sizeof(T)
    char buf[N];
    T obj;   // obj initialized to its original value
    memcpy(buf, &obj, N);
		// between these two calls to memcpy,
		// obj might be modified
    memcpy(&obj, buf, N);
		// at this point, each subobject of obj of scalar type
		// holds its original value
end example]

Now, supposing that the complete POD object type T in the example above is POD_bomb, and we cannot any more count on the assertions made in the comments to the example. Given a standard conforming implementation, the code will not even compile. And I see no legal way of copying the contents of an object of a complete object type POD_bomb into an array of char or unsigned char with memcpy or memmove without making use of the unary & operator. Except, of course, by means of an ugly construct like:

    struct  POD_without_ampersand  {
       POD_bomb   a_bomb;
    }  obj;
    #define N sizeof(POD_bomb)
    char buf[N];
    memcpy(buf, &obj, N);
    memcpy(&obj, buf, N);

The fact that the definition of a POD class allows for POD classes for which a user-defined operator& is defined, may also present major obstacles to implementers of the offsetof macro from <cstddef>

17.2 [support.types] paragraph 5 says:

The macro offsetof accepts a restricted set of type arguments in this International Standard. type shall be a POD structure or a POD union (Clause 11 [class]). The result of applying the offsetof macro to a field that is a static data member or a function is undefined."

Consider a well-formed C++ program below:

    #include <cstddef>
    #include <iostream>


    struct  POD_bomb  {
       int   m_value1;
       int   m_value2;
       int  operator&()
       {   return  m_value1++;   }
       int  operator&() const
       {   return  m_value1 + m_value2;   }
    };


    // POD_struct is a yet another example of a POD-struct.
    struct  POD_struct  {
       POD_bomb   m_nonstatic_bomb1;
       POD_bomb   m_nonstatic_bomb2;
    };


    int  main()
    {

       std::cout << "offset of m_nonstatic_bomb2: " << offsetof(POD_struct,
           m_nonstatic_bomb2) << '\n';
       return  0;

    }

See Jens Maurer's paper 01-0038=N1324 for an analysis of this issue.

Notes from 10/01 meeting:

A consensus was forming around the idea of disallowing operator& in POD classes when it was noticed that it is permitted to declare global-scope operator& functions, which cause the same problems. After more discussion, it was decided that such functions should not be prohibited in POD classes, and implementors should simply be required to "get the right answer" in constructs such as offsetof and va_start that are conventionally implemented using macros that use the "&" operator. It was noted that one can cast the original operand to char & to de-type it, after which one can use the built-in "&" safely.

Proposed resolution:




284. qualified-ids in class declarations

Section: Clause 11  [class]     Status: CD1     Submitter: Mike Miller     Date: 01 May 2001

[Moved to DR at October 2002 meeting.]

Although 9.3.4 [dcl.meaning] requires that a declaration of a qualified-id refer to a member of the specified namespace or class and that the member not have been introduced by a using-declaration, it applies only to names declared in a declarator. It is not clear whether there is existing wording enforcing the same restriction for qualified-ids in class-specifiers and elaborated-type-specifiers or whether additional wording is required. Once such wording is found/created, the proposed resolution of issue 275 must be modified accordingly.

Notes from 10/01 meeting:

The sentiment was that this should be required on class definitions, but not on elaborated type specifiers in general (which are references, not declarations). We should also make sure we consider explicit instantiations, explicit specializations, and friend declarations.

Proposed resolution (10/01):

Add after the end of 11.3 [class.name] paragraph 3:

When a nested-name-specifier is specified in a class-head or in an elaborated-type-specifier, the resulting qualified name shall refer to a previously declared member of the class or namespace to which the nested-name-specifier refers, and the member shall not have been introduced by a using-declaration in the scope of the class or namespace nominated by the nested-name-specifier.



327. Use of "structure" without definition

Section: Clause 11  [class]     Status: CD1     Submitter: James Kanze     Date: 9 Dec 2001

[Voted into WP at April, 2007 meeting.]

In Clause 11 [class] paragraph 4, the first sentence says "A structure is a class definition defined with the class-key struct". As far as I know, there is no such thing as a structure in C++; it certainly isn't listed as one of the possible compound types in 6.8.3 [basic.compound]. And defining structures opens the question of whether a forward declaration is a structure or not. The parallel here with union (which follows immediately) suggests that structures and classes are really different things, since the same wording is used, and classes and unions do have some real differences, which manifest themselves outside of the definition. It also suggests that since one can't forward declare union with class and vice versa, the same should hold for struct and class -- I believe that the intent was that one could use struct and class interchangeably in forward declaration.

Suggested resolution:

I suggest something like the following:

If a class is defined with the class-key class, its members and base classes are private by default. If a class is defined with the class-key struct, its members and base classes are public by default. If a class is defined with the class-key union, its members are public by default, and it holds only one data member at a time. Such classes are called unions, and obey a number of additional restrictions, see 11.5 [class.union].

Proposed resolution (April, 2006):

This issue is resolved by the resolution of issue 538.




379. Change "class declaration" to "class definition"

Section: Clause 11  [class]     Status: CD1     Submitter: Jens Maurer     Date: 21 Oct 2002

[Voted into WP at March 2004 meeting.]

The ARM used the term "class declaration" to refer to what would usually be termed the definition of the class. The standard now often uses "class definition", but there are some surviving uses of "class declaration" with the old meaning. They should be found and changed.

Proposed resolution (April 2003):

Replace in 6.2 [basic.def] paragraph 2

A declaration is a definition unless it declares a function without specifying the function's body (9.5 [dcl.fct.def]), it contains the extern specifier (9.2.2 [dcl.stc]) or a linkage-specification [Footnote: Appearing inside the braced-enclosed declaration-seq in a linkage-specification does not affect whether a declaration is a definition. --- end footnote] (9.11 [dcl.link]) and neither an initializer nor a function-body, it declares a static data member in a class declaration definition (11.4.9 [class.static]), it is a class name declaration (11.3 [class.name]), or it is a typedef declaration (9.2.4 [dcl.typedef]), a using-declaration (9.9 [namespace.udecl]), or a using-directive (9.8.4 [namespace.udir]).

Replace in 9.2.3 [dcl.fct.spec] paragraphs 5 and 6

The virtual specifier shall only be used in declarations of nonstatic class member functions that appear within a member-specification of a class declaration definition; see 11.7.3 [class.virtual].

The explicit specifier shall be used only in declarations of constructors within a class declaration definition; see 11.4.8.2 [class.conv.ctor].

Replace in 9.2.4 [dcl.typedef] paragraph 4

A typedef-name that names a class is a class-name (11.3 [class.name]). If a typedef-name is used following the class-key in an elaborated-type-specifier (9.2.9.4 [dcl.type.elab]) or in the class-head of a class declaration definition (Clause 11 [class]), or is used as the identifier in the declarator for a constructor or destructor declaration (11.4.5 [class.ctor], 11.4.7 [class.dtor]), the program is ill-formed.

Replace in _N4868_.9.8.2.3 [namespace.memdef] paragraph 3

The name of the friend is not found by simple name lookup until a matching declaration is provided in that namespace scope (either before or after the class declaration definition granting friendship).

Replace in 9.3.4.3 [dcl.ref] paragraph 4

There shall be no references to references, no arrays of references, and no pointers to references. The declaration of a reference shall contain an initializer (9.4.4 [dcl.init.ref]) except when the declaration contains an explicit extern specifier (9.2.2 [dcl.stc]), is a class member (11.4 [class.mem]) declaration within a class declaration definition, or is the declaration of a parameter or a return type (9.3.4.6 [dcl.fct]); see 6.2 [basic.def].

Replace in 9.4.4 [dcl.init.ref] paragraph 3

The initializer can be omitted for a reference only in a parameter declaration (9.3.4.6 [dcl.fct]), in the declaration of a function return type, in the declaration of a class member within its class declaration definition (11.4 [class.mem]), and where the extern specifier is explicitly used.

Replace in 11.3 [class.name] paragraph 2

A class definition declaration introduces the class name into the scope where it is defined declared and hides any class, object, function, or other declaration of that name in an enclosing scope (6.4 [basic.scope]). If a class name is declared in a scope where an object, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier (6.5.6 [basic.lookup.elab]).

Replace in 11.4.9 [class.static] paragraph 4

Static members obey the usual class member access rules ( 11.8 [class.access]). When used in the declaration of a class member, the static specifier shall only be used in the member declarations that appear within the member-specification of the class declaration definition.

Replace in 11.4.12 [class.nest] paragraph 1

A class can be defined declared within another class. A class defined declared within another is called a nested class. The name of a nested class is local to its enclosing class. The nested class is in the scope of its enclosing class. Except by using explicit pointers, references, and object names, declarations in a nested class can use only type names, static members, and enumerators from the enclosing class.

Replace in 11.6 [class.local] paragraph 1

A class can be defined declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. Declarations in a local class can use only type names, static variables, extern variables and functions, and enumerators from the enclosing scope.

Replace in 11.7 [class.derived] paragraph 1

... The class-name in a base-specifier shall not be an incompletely defined class (Clause 11 [class]); this class is called a direct base class for the class being declared defined. During the lookup for a base class name, non-type names are ignored (_N4868_.6.4.10 [basic.scope.hiding]). If the name found is not a class-name, the program is ill-formed. A class B is a base class of a class D if it is a direct base class of D or a direct base class of one of D's base classes. A class is an indirect base class of another if it is a base class but not a direct base class. A class is said to be (directly or indirectly) derived from its (direct or indirect) base classes. [Note: See 11.8 [class.access] for the meaning of access-specifier.] Unless redefined redeclared in the derived class, members of a base class are also considered to be members of the derived class. The base class members are said to be inherited by the derived class. Inherited members can be referred to in expressions in the same manner as other members of the derived class, unless their names are hidden or ambiguous (6.5.2 [class.member.lookup]). [Note: the scope resolution operator :: (_N4567_.5.1.1 [expr.prim.general]) can be used to refer to a direct or indirect base member explicitly. This allows access to a name that has been redefined redeclared in the derived class. A derived class can itself serve as a base class subject to access control; see 11.8.3 [class.access.base]. A pointer to a derived class can be implicitly converted to a pointer to an accessible unambiguous base class (7.3.12 [conv.ptr]). An lvalue of a derived class type can be bound to a reference to an accessible unambiguous base class (9.4.4 [dcl.init.ref]).]

Replace in 11.7.2 [class.mi] paragraph 5

For another example,
class V { /* ... */ };
class A : virtual public V { /* ... */ };
class B : virtual public V { /* ... */ };
class C : public A, public B { /* ... */ };
for an object c of class type C, a single subobject of type V is shared by every base subobject of c that is declared to have has a virtual base class of type V.

Replace in the example in 6.5.2 [class.member.lookup] paragraph 6 (the whole paragraph was turned into a note by the resolution of core issue 39)

The names defined declared in V and the left hand instance of W are hidden by those in B, but the names defined declared in the right hand instance of W are not hidden at all.

Replace in 11.7.4 [class.abstract] paragraph 2

... A virtual function is specified pure by using a pure-specifier (11.4 [class.mem]) in the function declaration in the class declaration definition. ...

Replace in the footnote at the end of 11.8.3 [class.access.base] paragraph 1

[Footnote: As specified previously in 11.8 [class.access], private members of a base class remain inaccessible even to derived classes unless friend declarations within the base class declaration definition are used to grant access explicitly.]

Replace in _N3225_.11.3 [class.access.dcl] paragraph 1

The access of a member of a base class can be changed in the derived class by mentioning its qualified-id in the derived class declaration definition. Such mention is called an access declaration. ...

Replace in the example in 12.3 [over.over] paragraph 5

The initialization of pfe is ill-formed because no f() with type int(...) has been defined declared, and not because of any ambiguity.

Replace in C.6.6 [diff.dcl] paragraph 1

Rationale: Storage class specifiers don't have any meaning when associated with a type. In C++, class members can be defined declared with the static storage class specifier. Allowing storage class specifiers on type declarations could render the code confusing for users.

Replace in C.6.7 [diff.class] paragraph 3

In C++, a typedef name may not be redefined redeclared in a class declaration definition after being used in the declaration that definition
Drafting notes:

The resolution of core issue 45 (DR) deletes 11.8.8 [class.access.nest] paragraph 2.

The following occurrences of "class declaration" are not changed:




383. Is a class with a declared but not defined destructor a POD?

Section: Clause 11  [class]     Status: CD1     Submitter: Gennaro Prota     Date: 18 Sep 2002

[Voted into WP at March 2004 meeting.]

The standard (Clause 11 [class] par. 4) says that "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor."

Note that it says 'user-defined', not 'user-declared'. Is it the intent that if e.g. a copy assignment operator is declared but not defined, this does not (per se) prevent the class to be a POD-struct?

Proposed resolution (April 2003):

Replace in Clause 11 [class] paragraph 4

A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined declared copy assignment operator and no user-defined declared destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined declared copy assignment operator and no user-defined declared destructor.

Drafting note: The changes are shown relative to TC1, incorporating the changes from the resolution of core issue 148.




413. Definition of "empty class"

Section: Clause 11  [class]     Status: CD1     Submitter: Pete Becker     Date: 30 Apr 2003

[Voted into WP at April, 2007 meeting.]

The proposal says that value is true if "T is an empty class (10)". Clause 10 doesn't define an empty class, although it has a note that says a base class may "be of zero size (clause 9)" 9/3 says "Complete objects and member subobjects of class type shall have nonzero size." This has a footnote, which says "Base class subobjects are not so constrained."

The standard uses the term "empty class" in two places (9.4.2 [dcl.init.aggr]), but neither of those places defines it. It's also listed in the index, which refers to the page that opens clause 9, i.e. the nonzero size stuff cited above.

So, what's the definition of "empty class" that determines whether the predicate is_empty is true?

The one place where it's used is 9.4.2 [dcl.init.aggr] paragraph 8, which says (roughly paraphrased) that an aggregate initializer for an empty class must be "{}", and when such an initializer is used for an aggregate that is not an empty class the members are default-initialized. In this context it's pretty clear what's meant. In the type traits proposal it's not as clear, and it was probably intended to have a different meaning. The boost implementation, after it eliminates non-class types, determines whether the trait is true by comparing the size of a class derived from T to the size of an otherwise-identical class that is not derived from T.

Howard Hinnant: is_empty was created to find out whether a type could be derived from and have the empty base class optimization successfully applied. It was created in part to support compressed_pair which attempts to optimize away the space for one of its members in an attempt to reduce spatial overhead. An example use is:

  template <class T, class Compare = std::less<T> >
  class SortedVec
  {
  public:
  ...
  private:
    T* data_;
    compressed_pair<Compare, size_type> comp_;

    Compare&       comp()       {return comp_.first();}
    const Compare& comp() const {return comp_.first();}
    size_type&     sz()         {return comp_.second();}
    size_type      sz() const   {return comp_.second();}
  };

Here the compare function is optimized away via the empty base optimization if Compare turns out to be an "empty" class. If Compare turns out to be a non-empty class, or a function pointer, the space is not optimized away. is_empty is key to making this work.

This work built on Nathan's article: http://www.cantrip.org/emptyopt.html.

Clark Nelson: I've been looking at issue 413, and I've reached the conclusion that there are two different kinds of empty class. A class containing only one or more anonymous bit-field members is empty for purposes of aggregate initialization, but not (necessarily) empty for purposes of empty base-class optimization.

Of course we need to add a definition of emptiness for purposes of aggregate initialization. Beyond that, there are a couple of questions:

  1. Should the definition of emptiness used by the is_empty predicate be defined in a language clause or a library clause?
  2. Do we need to open a new core issue pointing out the fact that the section on aggregate initialization does not currently say that unnamed bit-fields are skipped?

Notes from the October, 2005 meeting:

There are only two places in the Standard where the phrase “empty class” appears, both in 9.4.2 [dcl.init.aggr] paragraph 8. Because it is not clear whether the definition of “empty for initialization purposes” is suitable for use in defining the is_empty predicate, it would be better just to avoid using the phrase in the language clauses. The requirements of 9.4.2 [dcl.init.aggr] paragraph 8 appear to be redundant; paragraph 6 says that an initializer-list must have no more initializers than the number of elements to initialize, so an empty class already requires an empty initializer-list, and using an empty initializer-list with a non-empty class is covered adequately by paragraph 7's description of the handling of an initializer-list with fewer initializers than the number of members to initialize.

Proposed resolution (October, 2005):

  1. Change 9.4.2 [dcl.init.aggr] paragraph 5 by inserting the indicated text:

  2. Static data members and anonymous bit fields are not considered members of the class for purposes of aggregate initialization. [Example:

        struct A {
            int i;
            static int s;
            int j;
            int :17;
            int k;
        } a = { 1 , 2 , 3 };
    

    Here, the second initializer 2 initializes a.j and not the static data member A::s, and the third initializer 3 initializes a.k and not the padding before it.end example]

  3. Delete 9.4.2 [dcl.init.aggr] paragraph 8:

  4. An initializer for an aggregate member that is an empty class shall have the form of an empty initializer-list {}. [Example:

        struct S { };
        struct A {
            S s;
            int i;
        } a = { { } , 3 };
    

    end example] An empty initializer-list can be used to initialize any aggregate. If the aggregate is not an empty class, then each member of the aggregate shall be initialized with a value of the form T() (7.6.1.4 [expr.type.conv]), where T represents the type of the uninitialized member.

This resolution also resolves issue 491.

Additional note (October, 2005):

Deleting 9.4.2 [dcl.init.aggr] paragraph 8 altogether may not be a good idea. It would appear that, in its absence, the initializer elision rules of paragraph 11 would allow the initializer for a in the preceding example to be written { 3 } (because the empty-class member s would consume no initializers from the list).

Proposed resolution (October, 2006):

(Drafting note: this resolution also cleans up incorrect references to syntactic non-terminals in the nearby paragraphs.)

  1. Change 9.4.2 [dcl.init.aggr] paragraph 4 as indicated:

    An array of unknown size initialized with a brace-enclosed initializer-list containing n initializers initializer-clauses, where n shall be greater than zero... An empty initializer list {} shall not be used as the initializer initializer-clause for an array of unknown bound.
  2. Change 9.4.2 [dcl.init.aggr] paragraph 5 by inserting the indicated text:

    Static data members and anonymous bit fields are not considered members of the class for purposes of aggregate initialization. [Example:

        struct A {
            int i;
            static int s;
            int j;
            int :17;
            int k;
        } a = { 1 , 2 , 3 };
    

    Here, the second initializer 2 initializes a.j and not the static data member A::s, and the third initializer 3 initializes a.k and not the anonymous bit field before it.end example]

  3. Change 9.4.2 [dcl.init.aggr] paragraph 6 as indicated:

    An initializer-list is ill-formed if the number of initializers initializer-clauses exceeds the number of members...
  4. Change 9.4.2 [dcl.init.aggr] paragraph 7 as indicated:

    If there are fewer initializers initializer-clauses in the list than there are members...
  5. Replace 9.4.2 [dcl.init.aggr] paragraph 8:

    An initializer for an aggregate member that is an empty class shall have the form of an empty initializer-list {}. [Example:

        struct S { };
        struct A {
            S s;
            int i;
        } a = { { } , 3 };
    

    end example] An empty initializer-list can be used to initialize any aggregate. If the aggregate is not an empty class, then each member of the aggregate shall be initialized with a value of the form T() (7.6.1.4 [expr.type.conv]), where T represents the type of the uninitialized member.

    with:

    If an aggregate class C contains a subaggregate member m that has no members for purposes of aggregate initialization, the initializer-clause for m shall not be omitted from an initializer-list for an object of type C unless the initializer-clauses for all members of C following m are also omitted. [Example:

        struct S { } s;
        struct A {
            S s1;
            int i1;
            S s2;
            int i2;
            S s3;
            int i3;
        } a = {
            { },   // Required initialization
            0,
            s,     // Required initialization
            0
        };         // Initialization not required for A::s3 because A::i3 is also not initialized
    

    end example]

  6. Change 9.4.2 [dcl.init.aggr] paragraph 10 as indicated:

    When initializing a multi-dimensional array, the initializers initializer-clauses initialize the elements...
  7. Change 9.4.2 [dcl.init.aggr] paragraph 11 as indicated:

    Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializers initializer-clauses initializes the members of a subaggregate; it is erroneous for there to be more initializers initializer-clauses than members. If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializers initializer-clauses from the list are taken to initialize the members of the subaggregate; any remaining initializers initializer-clauses are left to initialize the next member of the aggregate of which the current subaggregate is a member. [Example:...
  8. Change 9.4.2 [dcl.init.aggr] paragraph 12 as indicated:

    All implicit type conversions (7.3 [conv]) are considered when initializing the aggregate member with an initializer from an initializer-list assignment-expression. If the initializer assignment-expression can initialize a member, the member is initialized. Otherwise, if the member is itself a non-empty subaggregate, brace elision is assumed and the initializer assignment-expression is considered for the initialization of the first member of the subaggregate. [Note: As specified above, brace elision cannot apply to subaggregates with no members for purposes of aggregate initialization; an initializer-clause for the entire subobject is required. —end note] [Example:... Braces are elided around the initializer initializer-clause for b.a1.i...
  9. Change 9.4.2 [dcl.init.aggr] paragraph 15 as indicated:

    When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer initializer-clause for the first member of the union...
  10. Change 9.4.2 [dcl.init.aggr] paragraph 16 as indicated:

    [Note: as As described above, the braces around the initializer initializer-clause for a union member can be omitted if the union is a member of another aggregate. —end note]

(Note: this resolution also resolves issue 491.)




538. Definition and usage of structure, POD-struct, POD-union, and POD class

Section: Clause 11  [class]     Status: CD1     Submitter: Alisdair Meredith     Date: 10 August 2005

[Voted into WP at April, 2007 meeting.]

There are several problems with the terms defined in Clause 11 [class] paragraph 4:

A structure is a class defined with the class-key struct; its members and base classes (11.7 [class.derived]) are public by default ( 11.8 [class.access]). A union is a class defined with the class-key union; its members are public by default and it holds only one data member at a time (11.5 [class.union]). [Note: aggregates of class type are described in 9.4.2 [dcl.init.aggr]. —end note] A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-declared copy assignment operator and no user-declared destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-declared copy assignment operator and no user-declared destructor. A POD class is a class that is either a POD-struct or a POD-union.
  1. Although the term structure is defined here, it is used only infrequently throughout the Standard, often apparently inadvertently and consequently incorrectly:

    There does not appear to be a reason for defining the term structure. The one reference where it is arguably useful, in the note in 7.6.1.5 [expr.ref], could be rewritten as something like, “'class objects' may be defined using the class, struct, or union class-keys; see Clause 11 [class].”

  2. Based on its usage later in the paragraph and elsewhere, “POD-struct” appears to be intended to exclude unions. However, the definition of “aggregate class” in 9.4.2 [dcl.init.aggr] paragraph 1 includes unions. Furthermore, the name itself is confusing, leading to the question of whether it was intended that only classes defined using struct could be POD-structs or if class-classes are included. The definition should probably be rewritten as, “A POD-struct is an aggregate class defined with the class-key struct or the class-key class that has no...

  3. In most references outside Clause 11 [class], POD-struct and POD-union are mentioned together and treated identically. These references should be changed to refer to the unified term, “POD class.”

  4. Noted in passing: 17.2 [support.types] paragraph 4 refers to the undefined terms “POD structure” and (unhyphenated) “POD union;” the pair should be replaced by a single reference to “POD class.”

Proposed resolution (April, 2006):

  1. Change Clause 11 [class] paragraph 4 as indicated:

    A structure is a class defined with the class-key struct; its members and base classes (11.7 [class.derived]) are public by default ( 11.8 [class.access]). A union is a class defined with the class-key union; its members are public by default and it holds only one data member at a time (11.5 [class.union]). [Note: aggregates of class type are described in 9.4.2 [dcl.init.aggr]. —end note] A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-declared copy assignment operator and no user-declared destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-declared copy assignment operator and no user-declared destructor. A POD class is a class that is either a POD-struct or a POD-union. A POD class is an aggregate class that has no non-static data members of non-POD type (or array of such a type) or reference, and has no user-declared copy assignment operator and no user-declared destructor. A POD-struct is a POD class defined with the class-key struct or the class-key class. A POD-union is a POD class defined with the class-key union.
  2. Change 11.8.3 [class.access.base] paragraph 2 as indicated:

    In the absence of an access-specifier for a base class, public is assumed when the derived class is declared defined with the class-key struct and private is assumed when the class is declared defined with the class-key class. [Example:...
  3. Delete the note in 7.6.1.5 [expr.ref] paragraph 4:

    [Note: “class objects” can be structures (11.4 [class.mem]) and unions (11.5 [class.union]). Classes are discussed in Clause 11 [class]. —end note]
  4. Change the commentary in the example in 11.4 [class.mem] paragraph 11 as indicated:

    ...an integer, and two pointers to similar structures objects of the same type. Once this definition...

    ...the count member of the structure object to which sp points; s.left refers to the left subtree pointer of the structure object s; and...

  5. Change _N4567_.17.3 [definitions] “iostream class templates” as indicated:

    ...the argument traits is a structure class which defines additional characteristics...
  6. Change 17.6 [support.dynamic] paragraph 4 as indicated:

    If type is not a POD structure or a POD union POD class (clause 9), the results are undefined.
  7. Change the third bullet of Clause Annex B [implimits] paragraph 2 as indicated:

  8. Change the nineteenth bullet of Clause Annex B [implimits] paragraph 2 as indicated:

  9. Change the twenty-first bullet of Clause Annex B [implimits] paragraph 2 as indicated:

  10. Change C.7 [diff.library] paragraph 6 as indicated:

    The C++ Standard library provides 2 standard structures structs from the C library, as shown in Table 126.
  11. Change the last sentence of 6.8 [basic.types] paragraph 10 as indicated:

    Scalar types, POD-struct types, POD-union types POD classes (Clause 11 [class]), arrays of such types and cv-qualified versions of these types (6.8.4 [basic.type.qualifier]) are collectively called POD types.

    Drafting note: Do not change 6.8 [basic.types] paragraph 11, because it's a note and the definition of “layout-compatible” is separate for POD-struct and POD-union in 11.4 [class.mem].

(This resolution also resolves issue 327.)




568. Definition of POD is too strict

Section: Clause 11  [class]     Status: CD1     Submitter: Matt Austern     Date: 20 March 2006

[Voted into the WP at the July, 2007 meeting as part of paper J16/07-0202 = WG21 N2342.]

A POD struct (Clause 11 [class] paragraph 4) is “an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types), or reference, and that has no user-defined copy assignment operator and no user-defined destructor.” Meanwhile, an aggregate class (9.4.2 [dcl.init.aggr] paragraph 1) must have “no user-declared constructors, no private or protecte non-static data members, no base classes, and no virtual functions.”

This is too strict. The whole reason we define the notion of POD is for the layout compatibility guarantees in 11.4 [class.mem] paragraphs 14-17 and the byte-for-byte copying guarantees of 6.8 [basic.types] paragraph 2. None of those guarantees should be affected by the presence of ordinary constructors, any more than they're affected by the presence of any other member function. It’s silly for the standard to make layout and memcpy guarantees for this class:

 struct A {
    int n;
 };

but not for this one:

  struct B {
    int n;
    B(n_) : n(n_) { }
  };

With either A or B, it ought to be possible to save an array of those objects to disk with a single call to Unix’s write(2) system call or the equivalent. At present the standard says that it’s legal for A but not B, and there isn’t any good reason for that distinction.

Suggested resolution:

The following doesn’t fix all problems (in particular it still doesn’t let us treat pair<int, int> as a POD), but at least it goes a long way toward fixing the problem: in 9.4.2 [dcl.init.aggr] paragraph 1, change “no user-declared constructors” to “no nontrivial default constructor and no user-declared copy constructor.”

(Yes, I’m aware that this proposed change would also allow brace initialization for some types that don't currently allow it. I consider this to be a feature, not a bug.)

Mike Miller: I agree that something needs to be done about “POD,” but I’m not sure that this is it. My own take is that “POD” is used for too many different things — things that are related but not identical — and the concept should be split. The current definition is useful, as is, for issues regarding initialization and lifetime. For example, I wouldn’t want to relax the prohibition of jumping over a constructor call in 8.8 [stmt.dcl] (which is currently phrased in terms of POD types). On the other hand, I agree that the presence of a user-declared constructor says nothing about layout and bitwise copying. This needs (IMHO) a non-trivial amount of further study to determine how many categories we need (instead of just POD versus non-POD), which guarantees and prohibitions go with which category, the interaction of “memcpy initialization” (for want of a better term) with object lifetime, etc.

(See paper J16/06-0172 = WG21 N2102.)

Proposed resolution (April, 2007):

Adoption of the POD proposal (currently J16/07-0090 = WG21 N2230) will resolve this issue.




417. Using derived-class qualified name in out-of-class nested class definition

Section: 11.3  [class.name]     Status: CD1     Submitter: Jon Caves     Date: 19 May 2003

[Voted into WP at October 2004 meeting.]

We had a user complain that our compiler was allowing the following code:

  struct B {
    struct S;
  };

  struct D : B { };

  struct D::S {
  };

We took one look at the code and made the reasonable (I would claim) assumption that this was indeed a bug in our compiler. Especially as we had just fixed a very similar issue with the definition of static data members.

Imagine our surprise when code like this showed up in Boost and that every other compiler we tested accepts this code. So is this indeed legal (it seems like it must be) and if so is there any justification for this beyond 6.5.5.2 [class.qual]?

John Spicer: The equivalent case for a member function is covered by the declarator rules in 9.3.4 [dcl.meaning] paragraph 1. The committee has previously run into cases where a restriction should apply to both classes and non-classes, but fails to do so because there is no equivalent of 9.3.4 [dcl.meaning] paragraph 1 for classes.

Given that, by the letter of the standard, I would say that this case is allowed.

Notes from October 2003 meeting:

We feel this case should get an error.

Proposed Resolution (October 2003):

Note that the change here interacts with issue 432.

Add the following as a new paragraph immediately following 6.4.2 [basic.scope.pdecl] paragraph 2:

The point of declaration for a class first declared by a class-specifier is immediately after the identifier or template-id (if any) in its class-head (Clause 11 [class]). The point of declaration for an enumeration is immediately after the identifier (if any) in its enum-specifier (9.7.1 [dcl.enum]).

Change point 1 of 6.4.6 [basic.scope.class] paragraph 1 to read:

The potential scope of a name declared in a class consists not only of the declarative region following the name's declarator point of declaration, but also of all function bodies, default arguments, and constructor ctor-initializers in that class (including such things in nested classes).

[Note that the preceding change duplicates one of the changes in the proposed resolution of issue 432.]

Change 13.9.3 [temp.explicit] paragraph 2 to read:

If the explicit instantiation is for a member function, a member class or a static data member of a class template specialization, the name of the class template specialization in the qualified-id for the member declarator name shall be a template-id.

Add the following as paragraph 5 of Clause 11 [class]:

If a class-head contains a nested-name-specifier, the class-specifier shall refer to a class that was previously declared directly in the class or namespace to which the nested-name-specifier refers (i.e., neither inherited nor introduced by a using-declaration), and the class-specifier shall appear in a namespace enclosing the previous declaration.

Delete 11.3 [class.name] paragraph 4 (this was added by issue 284):

When a nested-name-specifier is specified in a class-head or in an elaborated-type-specifier, the resulting qualified name shall refer to a previously declared member of the class or namespace to which the nested-name-specifier refers, and the member shall not have been introduced by a using-declaration in the scope of the class or namespace nominated by the nested-name-specifier.



328. Missing requirement that class member types be complete

Section: 11.4  [class.mem]     Status: CD1     Submitter: Michiel Salters     Date: 10 Dec 2001

[Voted into WP at March 2004 meeting.]

Is it legal to use an incomplete type (6.8 [basic.types] paragraph 6) as a class member, if no object of such class is ever created ?

And as a class template member, even if the template is instantiated, but no object of the instantiated class is created?

The consensus seems to be NO, but no wording was found in the standard which explicitly disallows it.

The problem seems to be that most of the restrictions on incomplete types are on their use in objects, but class members are not objects.

A possible resolution, if this is considered a defect, is to add to 6.3 [basic.def.odr] paragraph 4, (situations when T must be complete), the use of T as a member of a class or instantiated class template.

The thread on comp.std.c++ which brought up the issue was "Compiler differences: which is correct?", started 2001 11 30. <3c07c8fb$0$8507$ed9e5944@reading.news.pipex.net>

Proposed Resolution (April 2002, revised April 2003):

Change the first bullet of the note in 6.3 [basic.def.odr] paragraph 4 and add two new bullets following it, as follows:

Replace 11.4 [class.mem] paragraph 8 by:

Non-static (11.4.9 [class.static]) data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C.

See also 6.8 [basic.types] paragraph 6, which is relevant but not changed by the Proposed Resolution.




437. Is type of class allowed in member function exception specification?

Section: 11.4  [class.mem]     Status: CD1     Submitter: Cary Coutant     Date: 10 Oct 2003

[Voted into WP at April 2005 meeting.]

I've encountered a C++ program in which a member function wants to declare that it may throw an object of its own class, e.g.:

  class Foo {
  private:
     int val;
  public:
     Foo( int &initval ) { val = initval; };
     void throwit() throw(Foo) { throw (*this); };
  };

The compiler is complaining that Foo is an incomplete type, and can't be used in the exception specification.

My reading of the standard [basic.types] is inconclusive. Although it does state that the class declaration is considered complete when the closing brace is read, I believe it also intends that the member function declarations should not be semantically validated until the class has been completely declared.

If this isn't allowed, I don't know how else a member function could be declared to throw an object of its own class.

John Spicer: The type is considered complete within function bodies, but not in their declaration (see 11.4 [class.mem] paragraph 2).

Proposed Resolution:

Change 11.4 [class.mem] paragraph 2 as follows:

Within the class member-specification, the class is regarded as complete within function bodies, default arguments, exception-specifications, and constructor ctor-initializers (including such things in nested classes).

Rationale: Taken with 9.3.4.6 [dcl.fct] paragraph 6, the exception-specification is the only part of a function declaration/definition in which the class name cannot be used because of its putative incompleteness. There is no justification for singling out exception specifications this way; both in the function body and in a catch clause, the class type will be complete, so there is no harm in allowing the class name to be used in the exception-specification.




613. Unevaluated uses of non-static class members

Section: 11.4  [class.mem]     Status: CD1     Submitter: Herb Sutter     Date: 28 October 2006

[Voted into WP at April, 2007 meeting.]

According to 11.4 [class.mem] paragraph 9, the name of a non-static data member can only be used with an object reference (explicit or implied by the this pointer of a non-static member function) or to form a pointer to member. This restriction applies even in the operand of sizeof, although the operand is not evaluated and thus no object is needed to perform the operation. Consequently, determining the size of a non-static class member often requires a circumlocution like

    sizeof ((C*) 0)->m

instead of the simpler and more obvious (but incorrect)

    sizeof (C::m)

The CWG considered this question as part of issue 198 and decided at that time to retain the restriction on consistency grounds: the rule was viewed as applying uniformly to expressions, and making an exception for sizeof would require introducing a special-purpose “wart.”

The issue has recently resurfaced, in part due to the fact that the restriction would also apply to the decltype operator. Like the unary & operator to form a pointer to member, sizeof and decltype need neither an lvalue nor an rvalue, requiring solely the declarative information of the named operand. One possible approach would be to define the concept of “unevaluated operand” or the like, exempt unevaluated operands from the requirement for an object reference in 11.4 [class.mem] paragraph 9, and then define the operands of these operators as “unevaluated.”

Proposed resolution (April, 2007):

The wording is given in paper J16/07-0113 = WG21 N2253.




620. Declaration order in layout-compatible POD structs

Section: 11.4  [class.mem]     Status: CD1     Submitter: Martin Sebor     Date: 1 March 2007

[Voted into the WP at the July, 2007 meeting as part of paper J16/07-0202 = WG21 N2342.]

It should be made clear in 11.4 [class.mem] paragraph 15,

Two POD-struct (Clause 11 [class]) types are layout-compatible if they have the same number of non-static data members, and corresponding non-static data members (in order) have layout-compatible types (6.8 [basic.types]).

that “corresponding... (in order)” refers to declaration order and not the order in which the members are laid out in memory.

However, this raises the point that, in cases where an access-specifier is involved, the declaration and layout order can be different (see paragraph 12). Thus, for two POD-struct classes A and B,

    struct A {
        char c;
        int i;
    }
    struct B {
        char c;
      public:
        int i;
    };

a compiler could move B::i before B::c, but A::c must precede A::i. It does not seem reasonable that these two POD-structs would be considered layout-compatible, even though they satisfy the requirement that corresponding members in declaration order are layout-compatible.

One possibility would be to require that neither POD-struct have an access-specifier in order to be considered layout-compatible. (It's not sufficient to require that they have the same access-specifiers, because the compiler is not required to lay out the storage the same way for different classes.)

9.4.2 [dcl.init.aggr] paragraph 2 should also be clarified to make explicit that “increasing... member order” refers to declaration order.

Proposed resolution (April, 2007):

This issue will be resolved by the adoption of the POD proposal (currently J16/07-0090 = WG21 N2230). That paper does not propose a change to the wording of 9.4.2 [dcl.init.aggr] paragraph 2, but the CWG feels that the intent of that paragraph (that the initializers are used in declaration order) is clear enough not to require revision.




263. Can a constructor be declared a friend?

Section: 11.4.5  [class.ctor]     Status: CD1     Submitter: Martin Sebor     Date: 13 Nov 2000

[Voted into WP at April 2003 meeting.]

According to 11.4.5 [class.ctor] paragraph 1, a declaration of a constructor has a special limited syntax, in which only function-specifiers are allowed. A friend specifier is not a function-specifier, so one interpretation is that a constructor cannot be declared in a friend declaration.

(It should also be noted, however, that neither friend nor function-specifier is part of the declarator syntax, so it's not clear that anything conclusive can be derived from the wording of 11.4.5 [class.ctor].)

Notes from 04/01 meeting:

The consensus of the core language working group was that it should be permitted to declare constructors as friends.

Proposed Resolution (revised October 2002):

Change paragraph 1a in 6.5.5.2 [class.qual] (added by the resolution of issue 147) as follows:

If the nested-name-specifier nominates a class C, and the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C ( Clause 11 [class]), the name is instead considered to name the constructor of class C. Such a constructor name shall be used only in the declarator-id of a constructor definition declaration that appears outside of the class definition names a constructor....

Note: the above does not allow qualified names to be used for in-class declarations; see 9.3.4 [dcl.meaning] paragraph 1. Also note that issue 318 updates the same paragraph.

Change the example in 11.8.4 [class.friend], paragraph 4 as follows:

class Y {
  friend char* X::foo(int);
  friend X::X(char);   // constructors can be friends
  friend X::~X();      // destructors can be friends
  //...
};



326. Wording for definition of trivial constructor

Section: 11.4.5  [class.ctor]     Status: CD1     Submitter: James Kanze     Date: 9 Dec 2001

[Voted into WP at October 2003 meeting.]

In 11.4.5 [class.ctor] paragraph 5, the standard says "A constructor is trivial if [...]", and goes on to define a trivial default constructor. Taken literally, this would mean that a copy constructor can't be trivial (contrary to 11.4.5.3 [class.copy.ctor] paragraph 6). I suggest changing this to "A default constructor is trivial if [...]". (I think the change is purely editorial.)

Proposed Resolution (revised October 2002):

Change 11.4.5 [class.ctor] paragraph 5-6 as follows:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared user-declared constructor for class X, a default constructor is implicitly declared. An implicitly-declared implicitly-declared default constructor is an inline public member of its class. A default constructor is trivial if it is an implicitly-declared default constructor and if:

Otherwise, the default constructor is non-trivial.

Change 11.4.7 [class.dtor] paragraphs 3-4 as follows (the main changes are removing italics):

If a class has no user-declared user-declared destructor, a destructor is declared implicitly. An implicitly-declared implicitly-declared destructor is an inline public member of its class. A destructor is trivial if it is an implicitly-declared destructor and if:

Otherwise, the destructor is non-trivial non-trivial.

In 11.5 [class.union] paragraph 1, change "trivial constructor" to "trivial default constructor".

In 6.7.7 [class.temporary] paragraph 3, add to the reference to 11.4.5 [class.ctor] a second reference, to 11.4.5.3 [class.copy.ctor].




331. Allowed copy constructor signatures

Section: 11.4.5  [class.ctor]     Status: CD1     Submitter: Richard Smith     Date: 8 Jan 2002

[Voted into WP at October 2003 meeting.]

11.4.5 [class.ctor] paragraph 10 states

A copy constructor for a class X is a constructor with a first parameter of type X & or of type const X &. [Note: see 11.4.5.3 [class.copy.ctor] for more information on copy constructors.]

No mention is made of constructors with first parameters of types volatile X & or const volatile X &. This statement seems to be in contradiction with 11.4.5.3 [class.copy.ctor] paragraph 2 which states

A non-template constructor for class X is a copy constructor if its first parameter is of type X &, const X &, volatile X & or const volatile X &, ...

11.4.5.3 [class.copy.ctor] paragraph 5 also mentions the volatile versions of the copy constructor, and the comparable paragraphs for copy assignment (11.4.5.3 [class.copy.ctor] paragraphs 9 and 10) all allow volatile versions, so it seems that 11.4.5 [class.ctor] is at fault.

Proposed resolution (October 2002):

Change 11.4.5 [class.ctor] paragraph 10 from

A copy constructor for a class X is a constructor with a first parameter of type X& or of type const X&. [Note: see 11.4.5.3 [class.copy.ctor] for more information on copy constructors. ]
to (note that the dropping of italics is intentional):
A copy constructor (11.4.5.3 [class.copy.ctor]) is used to copy objects of class type.




683. Requirements for trivial subobject special functions

Section: 11.4.5.3  [class.copy.ctor]     Status: CD1     Submitter: Jens Maurer     Date: 13 March, 2008

[Voted into the WP at the September, 2008 meeting (resolution in paper N2757).]

Part of the decision regarding whether a class has a trivial special function (copy constructor, copy assignment operator, default constructor) is whether its base and member subobjects have corresponding trivial member functions. However, with the advent of defaulted functions, it is now possible for a single class to have both trivial and nontrivial overloads for those functions. For example,

    struct B {
       B(B&) = default;    // trivial
       B(const B&);        // non-trivial, because user-provided
    };

    struct D : B { };

Although B has a trivial copy constructor and thus satisfies the requirements in 11.4.5.3 [class.copy.ctor] paragraph 6, the copy constructor in B that would be called by the implicitly-declared copy constructor in D is not trivial. This could be fixed either by requiring that all the subobject's copy constructors (or copy assignment operators, or default constructors) be trivial or that the one that would be selected by overload resolution be trivial.

Proposed resolution (July, 2008):

Change 9.5 [dcl.fct.def] paragraph 9 as follows:

... A special member function that would be implicitly defined as deleted shall not be explicitly defaulted. If a special member function for a class X is defaulted on its first declaration, no other special member function of the same kind (default constructor, copy constructor, or copy assignment operator) shall be declared in class X. A special member function is user-provided...

Notes from the September, 2008 meeting:

The resolution adopted as part of paper N2757 differs from the July, 2008 proposed resolution by allowing defaulted and user-provided special member functions to coexist. Instead, a trivial class is defined as having no non-trivial copy constructors or copy assignment operators, and a trivial copy constructor or assignment operator is defined as invoking only trivial copy operations for base and member subobjects.




244. Destructor lookup

Section: 11.4.7  [class.dtor]     Status: CD1     Submitter: John Spicer     Date: 6 Sep 2000

[Moved to DR at October 2002 meeting.]

11.4.7 [class.dtor] contains this example:

    struct B {
        virtual ~B() { }
    };
    struct D : B {
        ~D() { }
    };

    D D_object;
    typedef B B_alias;
    B* B_ptr = &D_object;

    void f() {
        D_object.B::~B();               // calls B's destructor
        B_ptr->~B();                    // calls D's destructor
        B_ptr->~B_alias();              // calls D's destructor
        B_ptr->B_alias::~B();           // calls B's destructor
        B_ptr->B_alias::~B_alias();     // error, no B_alias in class B
    }

On the other hand, 6.5.5 [basic.lookup.qual] contains this example:

    struct C {
        typedef int I;
    };
    typedef int I1, I2;
    extern int* p;
    extern int* q;
    p->C::I::~I();       // I is looked up in the scope of C
    q->I1::~I2();        // I2 is looked up in the scope of
                         // the postfix-expression
    struct A {
        ~A();
    };
    typedef A AB;
    int main()
    {
        AB *p;
        p->AB::~AB();    // explicitly calls the destructor for A
    }

Note that

     B_ptr->B_alias::~B_alias();

is claimed to be an error, while the equivalent

     p->AB::~AB();

is claimed to be well-formed.

I believe that clause 3 is correct and that clause 12 is in error. We worked hard to get the destructor lookup rules in clause 3 to be right, and I think we failed to notice that a change was also needed in clause 12.

Mike Miller:

Unfortunately, I don't believe 6.5.5 [basic.lookup.qual] covers the case of p->AB::~AB(). It's clearly intended to do so, as evidenced by 6.5.5.2 [class.qual] paragraph 1 ("a destructor name is looked up as specified in 6.5.5 [basic.lookup.qual]"), but I don't think the language there does so.

The relevant paragraph is 6.5.5 [basic.lookup.qual] paragraph 5. (None of the other paragraphs in that section deal with this topic at all.) It has two parts. The first is

If a pseudo-destructor-name (_N4778_.7.6.1.4 [expr.pseudo]) contains a nested-name-specifier, the type-names are looked up as types in the scope designated by the nested-name-specifier.

This sentence doesn't apply, because ~AB isn't a pseudo-destructor-name. _N4778_.7.6.1.4 [expr.pseudo] makes clear that this syntactic production (7.6.1 [expr.post] paragraph 1) only applies to cases where the type-name is not a class-name. p->AB::~AB is covered by the production using id-expression.

The second part of 6.5.5 [basic.lookup.qual] paragraph 5 says

In a qualified-id of the form:

    ::opt nested-name-specifier ~ class-name

where the nested-name-specifier designates a namespace name, and in a qualified-id of the form:

    ::opt nested-name-specifier class-name :: ~ class-name

the class-names are looked up as types in the scope designated by the nested-name-specifier.

This wording doesn't apply, either. The first one doesn't because the nested-name-specifier is a class-name, not a namespace name. The second doesn't because there's only one layer of qualification.

As far as I can tell, there's no normative text that specifies how the ~AB is looked up in p->AB::~AB(). 6.5.5.2 [class.qual], where all the other class member qualified lookups are handled, defers to 6.5.5 [basic.lookup.qual], and 6.5.5 [basic.lookup.qual] doesn't cover the case.

See also issue 305.

Jason Merrill: My thoughts on the subject were that the name we use in a destructor call is really meaningless; as soon as we see the ~ we know what the user means, all we're doing from that point is testing their ability to name the destructor in a conformant way. I think that everyone will agree that

  anything::B::~B()
should be well-formed, regardless of the origins of the name "B". I believe that the rule about looking up the second "B" in the same context as the first was intended to provide this behavior, but to me this seems much more heavyweight than necessary. We don't need a whole new type of lookup to be able to use the same name before and after the ~; we can just say that if the two names match, the call is well-formed. This is significantly simpler to express, both in the standard and in an implementation.

Anyone writing two different names here is either deliberately writing obfuscated code, trying to call the destructor of a nested class, or fighting an ornery compiler (i.e. one that still wants to see B_alias::~B()). I think we can ignore the first case. The third would be handled by reverting to the old rule (look up the name after ~ in the normal way) with the lexical matching exception described above -- or we could decide to break such code, do no lookup at all, and only accept a matching name. In a good implementation, the second should probably get an error message telling them to write Outer::Inner::~Inner instead.

We discussed this at the meetings, but I don't remember if we came to any sort of consensus on a direction. I see three options:

  1. Stick with the status quo, i.e. the special lookup rule such that if the name before ::~ is a class name, the name after ::~ is looked up in the same scope as the previous one. If we choose this option, we just need better wording that actually expresses this, as suggested in the issue list. This option breaks old B_alias::~B code where B_alias is declared in a different scope from B.
  2. Revert to the old rules, whereby the name after ::~ is looked up just like a name after ::, with the exception that if it matches the name before ::~ then it is considered to name the same class. This option supports old code and code that writes B_alias::~B_alias. It does not support the q->I1::~I2 usage of 6.5.5 [basic.lookup.qual], but that seems like deliberate obfuscation. This option is simpler to implement than #1.
  3. Do no lookup for a name after ::~; it must match the name before. This breaks old code as #1, but supports the most important case where the names match. This option may be slightly simpler to implement than #2. It is certainly easier to teach.

My order of preference is 2, 3, 1.

Incidentally, it seems to me oddly inconsistent to allow Namespace::~Class, but not Outer::~Inner. Prohibiting the latter makes sense from the standpoint of avoiding ambiguity, but what was the rationale for allowing the former?

John Spicer: I agree that allowing Namespace::~Class is odd. I'm not sure where this came from. If we eliminated that special case, then I believe the #1 rule would just be that in A::B1::~B2 you look up B1 and B2 in the same place in all cases.

I don't like #2. I don't think the "old" rules represent a deliberate design choice, just an error in the way the lookup was described. The usage that rule permits p->X::~Y (where Y is a typedef to X defined in X), but I doubt people really do that. In other words, I think that #1 a more useful special case than #2 does, not that I think either special case is very important.

One problem with the name matching rule is handling cases like:

  A<int> *aip;

  aip->A<int>::~A<int>();  // should work
  aip->A<int>::~A<char>(); // should not
I would favor #1, while eliminating the special case of Namespace::~Class.

Proposed resolution (10/01):

Replace the normative text of 6.5.5 [basic.lookup.qual] paragraph 5 after the first sentence with:

Similarly, in a qualified-id of the form:

    ::opt nested-name-specifieropt class-name :: ~ class-name
the second class-name is looked up in the same scope as the first.

In 11.4.7 [class.dtor] paragraph 12, change the example to

D D_object;
typedef B B_alias;
B* B_ptr = &D_object;

void f() {
  D_object.B::~B();                //  calls  B's destructor
  B_ptr->~B();                    //  calls  D's destructor
  B_ptr->~B_alias();              //  calls  D's destructor
  B_ptr->B_alias::~B();           //  calls  B's destructor
  B_ptr->B_alias::~B_alias();     //  calls  B's destructor
}

April 2003: See issue 399.




252. Looking up deallocation functions in virtual destructors

Section: 11.4.7  [class.dtor]     Status: CD1     Submitter: Steve Clamage     Date: 19 Oct 2000

[Moved to DR at 10/01 meeting.]

There is a mismatch between 11.4.7 [class.dtor] paragraph 11 and 11.4.11 [class.free] paragraph 4 regarding the lookup of deallocation functions in virtual destructors. 11.4.7 [class.dtor] says,

At the point of definition of a virtual destructor (including an implicit definition (11.4.5.3 [class.copy.ctor])), non-placement operator delete shall be looked up in the scope of the destructor's class (6.5.3 [basic.lookup.unqual]) and if found shall be accessible and unambiguous. [Note: this assures that an operator delete corresponding to the dynamic type of an object is available for the delete-expression (11.4.11 [class.free]). ]

The salient features to note from this description are:

  1. The lookup is "in the scope of the destructor's class," which implies that only members are found (cf 6.7.7 [class.temporary]). (The cross-reference would indicate otherwise, however, since it refers to the description of looking up unqualified names; this kind of lookup "spills over" into the surrounding scope.)
  2. Only non-placement operator delete is looked up. Presumably this means that a placement operator delete is ignored in the lookup.

On the other hand, 11.4.11 [class.free] says,

If a delete-expression begins with a unary :: operator, the deallocation function's name is looked up in global scope. Otherwise, if the delete-expression is used to deallocate a class object whose static type has a virtual destructor, the deallocation function is the one found by the lookup in the definition of the dynamic type's virtual destructor (11.4.7 [class.dtor]). Otherwise, if the delete-expression is used to deallocate an object of class T or array thereof, the static and dynamic types of the object shall be identical and the deallocation function's name is looked up in the scope of T. If this lookup fails to find the name, the name is looked up in the global scope. If the result of the lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function, the program is ill-formed.

Points of interest in this description include:

  1. For a class type with a virtual destructor, the lookup is described as being "in the definition of the dynamic type's virtual destructor," rather than "in the scope of the dynamic type." That is, the lookup is assumed to be an unqualified lookup, presumably terminating in the global scope.
  2. The assumption is made that the lookup in the virtual destructor was successful ("...the one found...", not "...the one found..., if any"). This will not be the case if the deallocation function was not declared as a member somewhere in the inheritance hierarchy.
  3. The lookup in the non-virtual-destructor case does find placement deallocation functions and can fail as a result.

Suggested resolution: Change the description of the lookup in 11.4.7 [class.dtor] paragraph 11 to match the one in 11.4.11 [class.free] paragraph 4.

Proposed resolution (10/00):

  1. Replace 11.4.7 [class.dtor] paragraph 11 with the following:

    At the point of definition of a virtual destructor (including an implicit definition), the non-array deallocation function is looked up in the scope of the destructor's class (6.5.2 [class.member.lookup]), and, if no declaration is found, the function is looked up in the global scope. If the result of this lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function, the program is ill-formed. [Note: this assures that a deallocation function corresponding to the dynamic type of an object is available for the delete-expression (11.4.11 [class.free]).]
  2. In 11.4.11 [class.free] paragraph 4, change

    ...the deallocation function is the one found by the lookup in the definition of the dynamic type's virtual destructor (11.4.7 [class.dtor]).

    to

    ...the deallocation function is the one selected at the point of definition of the dynamic type's virtual destructor (11.4.7 [class.dtor]).



272. Explicit destructor invocation and qualified-ids

Section: 11.4.7  [class.dtor]     Status: CD1     Submitter: Mike Miller     Date: 22 Feb 2001

[Moved to DR at 10/01 meeting.]

11.4.7 [class.dtor] paragraph 12 contains the following note:
an explicit destructor call must always be written using a member access operator (7.6.1.5 [expr.ref]); in particular, the unary-expression ~X() in a member function is not an explicit destructor call (7.6.2.2 [expr.unary.op]).

This note is incorrect, as an explicit destructor call can be written as a qualified-id, e.g., X::~X(), which does not use a member access operator.

Proposed resolution (04/01):

Change 11.4.7 [class.dtor] paragraph 12 as follows:

[Note: an explicit destructor call must always be written using a member access operator (7.6.1.5 [expr.ref]) or a qualified-id (_N4567_.5.1.1 [expr.prim.general]); in particular, the unary-expression ~X() in a member function is not an explicit destructor call (7.6.2.2 [expr.unary.op]).]



677. Deleted operator delete and virtual destructors

Section: 11.4.7  [class.dtor]     Status: CD1     Submitter: Mike Miller     Date: 15 February, 2008

[Voted into the WP at the September, 2008 meeting.]

Deallocation functions can't be virtual because they are static member functions; however, according to 11.4.11 [class.free] paragraph 7, they behave like virtual functions when the class's destructor is virtual:

Since member allocation and deallocation functions are static they cannot be virtual. [Note: however, when the cast-expression of a delete-expression refers to an object of class type, because the deallocation function actually called is looked up in the scope of the class that is the dynamic type of the object, if the destructor is virtual, the effect is the same.

Because the intent is to make any use of a deleted function diagnosable at compile time, a virtual deleted function can neither override nor be overridden by a non-deleted function, as described in 11.7.3 [class.virtual] paragraph 14:

A function with a deleted definition (9.5 [dcl.fct.def]) shall not override a function that does not have a deleted definition. Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition.

One would assume that a similar kind of prohibition is needed for deallocation functions in a class hierarchy with virtual destructors, but it's not clear that the current specification says that. 9.5 [dcl.fct.def] paragraph 10 says,

A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.

Furthermore, the deallocation function is looked up at the point of definition of a virtual destructor (11.4.7 [class.dtor] paragraph 11) , and the function found by this lookup is considered to be “used” (6.3 [basic.def.odr] paragraph 2). However, it's not completely clear that this “use” constitutes a “reference” in the sense of 9.5 [dcl.fct.def] paragraph 10, especially in a program in which an object of a type that would call that deallocation function is never deleted.

Suggested resolution:

Augment the list of lookup results from a virtual destructor that render a program ill-formed in 11.4.7 [class.dtor] paragraph 10 to include a deleted function:

If the result of this lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function or a function with a deleted definition (9.5 [dcl.fct.def]), the program is ill-formed.

Proposed resolution (June, 2008):

Change 11.4.7 [class.dtor] paragraph 10 as follows:

If the result of this lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function or a function with a deleted definition (9.5 [dcl.fct.def]), the program is ill-formed.



296. Can conversion functions be static?

Section: 11.4.8.3  [class.conv.fct]     Status: CD1     Submitter: Scott Meyers     Date: 5 Jul 2001

[Moved to DR at October 2002 meeting.]

May user-defined conversion functions be static? That is, should this compile?

    class Widget {
    public:
      static operator bool() { return true; }
    };

All my compilers hate it. I hate it, too. However, I don't see anything in 11.4.8.3 [class.conv.fct] that makes it illegal. Is this a prohibition that arises from the grammar, i.e., the grammar doesn't allow "static" to be followed by a conversion-function-id in a member function declaration? Or am I just overlooking something obvious that forbids static conversion functions?

Proposed Resolution (4/02):

Add to 11.4.8.3 [class.conv.fct] as a new paragraph 7:

Conversion functions cannot be declared static.



406. Static data member in class with name for linkage purposes

Section: 11.4.9.3  [class.static.data]     Status: CD1     Submitter: Jorgen Bundgaard     Date: 12 Mar 2003

[Voted into WP at March 2004 meeting.]

The following test program is claimed to be a negative C++ test case for "Unnamed classes shall not contain static data members", c.f. ISO/IEC 14882 section 11.4.9.3 [class.static.data] paragraph 5.

  struct B {
         typedef struct {
                 static int i;          // Is this legal C++ ?
         } A;
  };

  int B::A::i = 47;      // Is this legal C++ ?

We are not quite sure about what an "unnamed class" is. There is no exact definition in ISO/IEC 14882; the closest we can come to a hint is the wording of section 9.2.4 [dcl.typedef] paragraph 5, where it seems to be understood that a class-specifier with no identifier between "class" and "{" is unnamed. The identifier provided after "}" ( "A" in the test case above) is there for "linkage purposes" only.

To us, class B::A in the test program above seems "named" enough, and there is certainly a mechanism to provide the definition for B::A::i (in contrast to the note in section 11.4.9.3 [class.static.data] paragraph 5) .

Our position is therefore that the above test program is indeed legal C++. Can you confirm or reject this claim?

Herb Sutter replied to the submitter as follows: Here are my notes based on a grep for "unnamed class" in the standard:

So yes, an unnamed class is one where there is no identifier (class name) between the class-key and the {. This is also in harmony with the production for class-name in Clause 11 [class] paragraph 1:

Notes from the October 2003 meeting:

We agree that the example is not valid; this is an unnamed class. We will add wording to define an unnamed class. The note in 11.4.9.3 [class.static.data] paragraph 5 should be corrected or deleted.

Proposed Resolution (October 2003):

At the end of Clause 11 [class], paragraph 1, add the following:

A class-specifier where the class-head omits the optional identifier defines an unnamed class.

Delete the following from 11.4.9.3 [class.static.data] paragraph 5:

[ Note: this is because there is no mechanism to provide the definitions for such static data members. ]



454. When is a definition of a static data member required?

Section: 11.4.9.3  [class.static.data]     Status: CD1     Submitter: Gennaro Prota     Date: 18 Jan 2004

[Voted into WP at the October, 2006 meeting.]

As a result of the resolution of core issue 48, the current C++ standard is not in sync with existing practice and with user expectations as far as definitions of static data members having const integral or const enumeration type are concerned. Basically what current implementations do is to require a definition only if the address of the constant is taken. Example:

void f() {

  std::string s;
  ...

  // current implementations don't require a definition
  if (s.find('a', 3) == std::string::npos) {
   ...
  }

To the letter of the standard, though, the above requires a definition of npos, since the expression std::string::npos is potentially evaluated. I think this problem would be easily solved with simple changes to 11.4.9.3 [class.static.data] paragraph 4, 11.4.9.3 [class.static.data] paragraph 5 and 6.3 [basic.def.odr] paragraph 3.

Suggested resolution:

Replace 11.4.9.3 [class.static.data] paragraph 4 with:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be [note1] an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. No definition of the member is required, unless an lvalue expression that designates it is potentially evaluated and either used as operand to the built-in unary & operator [note 2] or directly bound to a reference.

If a definition exists, it shall be at namespace scope and shall not contain an initializer.

In 11.4.9.3 [class.static.data] paragraph 5 change

There shall be exactly one definition of a static data member that is used in a program; no diagnostic is required; see 3.2.

to

Except as allowed by 9.4.2 par. 4, there shall be exactly one definition of a static data member that is potentially evaluated (3.2) in a program; no diagnostic is required.

In 6.3 [basic.def.odr] paragraph 3 add, at the beginning:

Except for the omission allowed by 9.4.2, par. 4, ...

[note 1] Actually it shall be a "= followed by a constant-expression". This could probably be an editorial fix, rather than a separate DR.

[note 2] Note that this is the case when reinterpret_cast-ing to a reference, like in

struct X { static const int value = 0; };
const char & c = reinterpret_cast<const char&>(X::value);
See 7.6.1.10 [expr.reinterpret.cast]/10

More information, in response to a question about why issue 48 does not resolve the problem:

The problem is that the issue was settled in a way that solves much less than it was supposed to solve; that's why I decided to file, so to speak, a DR on a DR.

I understand this may seem a little 'audacious' on my part, but please keep reading. Quoting from the text of DR 48 (emphasis mine):

Originally, all static data members still had to be defined outside the class whether they were used or not.

But that restriction was supposed to be lifted [...]

In particular, if an integral/enum const static data member is initialized within the class, and its address is never taken, we agreed that no namespace-scope definition was required.

The corresponding resolution doesn't reflect this intent, with the definition being still required in most situations anyway: it's enough that the constant appears outside a place where constants are required (ignoring the obvious cases of sizeof and typeid) and you have to provide a definition. For instance:

  struct X {
   static const int c = 1;
  };

  void f(int n)
  {
   if (n == X::c)   // <-- potentially evaluated
    ...
  }

<start digression>

Most usages of non-enum BOOST_STATIC_COSTANTs, for instance, are (or were, last time I checked) non-conforming. If you recall, Paul Mensonides pointed out that the following template

// map_integral

template<class T, T V> struct map_integral : identity<T> {
  static const T value = V;
};

template<class T, T V> const T map_integral<T, V>::value;

whose main goal is to map the same couples (type, value) to the same storage, also solves the definition problem. In this usage it is an excellent hack (if your compiler is good enough), but IMHO still a hack on a language defect.

<end digression>

What I propose is to solve the issue according to the original intent, which is also what users expect and all compilers that I know of already do. Or, in practice, we would have a rule that exists only as words in a standard document.

PS: I've sent a copy of this to Mr. Adamczyk to clarify an important doubt that occurred to me while writing this reply:

if no definition is provided for an integral static const data member is that member an object? Paragraph 1.8/1 seems to say no, and in fact it's difficult to think it is an object without assuming/pretending that a region of storage exists for it (an object *is* a region of storage according to the standard).

I would think that when no definition is required we have to assume that it could be a non-object. In that case there's nothing in 3.2 which says what 'used' means for such an entity and the current wording would thus be defective. Also, since the name of the member is an lvalue and 3.10/2 says an lvalue refers to an object we would have another problem.

OTOH the standard could pretend it is always an object (though the compiler can optimize it away) and in this case it should probably make a special case for it in 3.2/2.

Notes from the March 2004 meeting:

We sort of like this proposal, but we don't feel it has very high priority. We're not going to spend time discussing it, but if we get drafting for wording we'll review it.

Proposed resolution (October, 2005):

  1. Change the first two sentences of 6.3 [basic.def.odr] paragraph 2 from:

    An expression is potentially evaluated unless it appears where an integral constant expression is required (see 7.7 [expr.const]), is the operand of the sizeof operator (7.6.2.5 [expr.sizeof]), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (7.6.1.8 [expr.typeid]). An object or non-overloaded function is used if its name appears in a potentially-evaluated expression.

    to

    An expression that is the operand of the sizeof operator (7.6.2.5 [expr.sizeof]) is unevaluated, as is an expression that is the operand of the typeid operator if it is not an lvalue of a polymorphic class type (7.6.1.8 [expr.typeid]); all other expressions are potentially evaluated. An object or non-overloaded function whose name appears as a potentially-evaluated expression is used, unless it is an object that satisfies the requirements for appearing in an integral constant expression (7.7 [expr.const]) and the lvalue-to-rvalue conversion (7.3.2 [conv.lval]) is immediately applied.
  2. Change the first sentence of 11.4.9.3 [class.static.data] paragraph 2 as indicated:

  3. If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which whose constant-expression shall be an integral constant expression (7.7 [expr.const]).



58. Signedness of bit fields of enum type

Section: 11.4.10  [class.bit]     Status: CD1     Submitter: Steve Adamczyk     Date: 13 Oct 1998

[Voted into WP at the October, 2006 meeting.]

Section 11.4.10 [class.bit] paragraph 4 needs to be more specific about the signedness of bit fields of enum type. How much leeway does an implementation have in choosing the signedness of a bit field? In particular, does the phrase "large enough to hold all the values of the enumeration" mean "the implementation decides on the signedness, and then we see whether all the values will fit in the bit field", or does it require the implementation to make the bit field signed or unsigned if that's what it takes to make it "large enough"?

(See also issue 172.)

Note (March, 2005): Clark Nelson observed that there is variation among implementations on this point.

Notes from April, 2005 meeting:

Although implementations enjoy a great deal of latitude in handling bit-fields, it was deemed more user-friendly to ensure that the example in paragraph 4 will work by requiring implementations to use an unsigned underlying type if the enumeration type has no negative values. (If the implementation is allowed to choose a signed representation for such bit-fields, the comparison against TRUE will be false.)

In addition, it was observed that there is an apparent circularity between 9.7.1 [dcl.enum] paragraph 7 and 11.4.10 [class.bit] paragraph 4 that should be resolved.

Proposed resolution (April, 2006):

  1. Replace 9.7.1 [dcl.enum] paragraph 7, deleting the embedded footnote 85, with the following:

    For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values in the range bmin to bmax, defined as follows: Let K be 1 for a two's complement representation and 0 for a one's complement or sign-magnitude representation. bmax is the smallest value greater than or equal to max(|emin|-K,|emax|) and equal to 2M-1, where M is a non-negative integer. bmin is zero if emin is non-negative and -(bmax+K) otherwise. The size of the smallest bit-field large enough to hold all the values of the enumeration type is max(M,1) if bmin is zero and M+1 otherwise. It is possible to define an enumeration that has values not defined by any of its enumerators.
  2. Add the indicated text to the second sentence of 11.4.10 [class.bit] paragraph 4:

    If the value of an enumerator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is large enough to hold all the values of that enumeration type (9.7.1 [dcl.enum]), the original enumerator value and the value of the bit-field shall compare equal.



436. Problem in example in 9.6 paragraph 4

Section: 11.4.10  [class.bit]     Status: CD1     Submitter: Roberto Santos     Date: 10 October 2003

[Voted into WP at October 2004 meeting.]

It looks like the example on 11.4.10 [class.bit] paragraph 4 has both the enum and function contributing the identifier "f" for the same scope.

  enum BOOL { f=0, t=1 };
  struct A {
    BOOL b:1;
  };
  A a;
  void f() {
    a.b = t;
    if (a.b == t) // shall yield true
    { /* ... */ }
  }

Proposed resolution:

Change the example at the end of 11.4.10 [class.bit]/4 from:

  enum BOOL { f=0, t=1 };
  struct A {
    BOOL b:1;
  };
  A a;
  void f() {
    a.b = t;
    if (a.b == t) // shall yield true
    { /* ... */ }
  }

To:

  enum BOOL { FALSE=0, TRUE=1 };
  struct A {
    BOOL b:1;
  };
  A a;
  void f() {
    a.b = TRUE;
    if (a.b == TRUE) // shall yield true
    { /* ... */ }
  }




198. Definition of "use" in local and nested classes

Section: 11.6  [class.local]     Status: CD1     Submitter: Erwin Unruh     Date: 27 Jan 2000

[Voted into WP at April 2003 meeting.]

11.6 [class.local] paragraph 1 says,

Declarations in a local class can use only type names, static variables, extern variables and functions, and enumerators from the enclosing scope.
The definition of when an object or function is "used" is found in 6.3 [basic.def.odr] paragraph 2 and essentially says that the operands of sizeof and non-polymorphic typeid operators are not used. (The resolution for issue 48 will add contexts in which integral constant expressions are required to the list of non-uses.)

This definition of "use" would presumably allow code like

    void foo() {
        int i;
        struct S {
            int a[sizeof(i)];
        };
    };
which is required for C compatibility.

However, the restrictions on nested classes in 11.4.12 [class.nest] paragraph 1 are very similar to those for local classes, and the example there explicitly states that a reference in a sizeof expression is a forbidden use (abbreviated for exposition):

    class enclose {
    public:
        int x;
        class inner {
            void f(int i)
            {
                int a = sizeof(x);  // error: refers to enclose::x
            }
        };
    };

[As a personal note, I have seen real-world code that was exactly like this; it was hard to persuade the author that the required writearound, sizeof(((enclose*) 0)->x), was an improvement over sizeof(x). —wmm]

Similarly, 11.4 [class.mem] paragraph 9 would appear to prohibit examples like the following:

    struct B {
        char x[10];
    };
    struct D: B {
        char y[sizeof(x)];
    };

Suggested resolution: Add cross-references to 6.3 [basic.def.odr] following the word "use" in both 11.4.12 [class.nest] and 11.6 [class.local] , and change the example in 11.4.12 [class.nest] to indicate that a reference in a sizeof expression is permitted. In 11.4 [class.mem] paragraph 9, "referred to" should be changed to "used" with a cross_reference to 6.3 [basic.def.odr].

Notes from 10/01 meeting:

It was noted that the suggested resolution did not make the sizeof() example in 11.4.12 [class.nest] valid. Although the reference to the argument of sizeof() is not regarded as a use, the right syntax must be used nonetheless to reference a non-static member from the enclosing class. The use of the member name by itself is not valid. The consensus within the core working group was that nothing should be done about this case. It was later discovered that 11.4.9 [class.static] paragraph 3 states that

The definition of a static member shall not use directly the names of the nonstatic members of its class or of a base class of its class (including as operands of the sizeof operator). The definition of a static member may only refer to these members to form pointer to members (7.6.2.2 [expr.unary.op]) or with the class member access syntax (7.6.1.5 [expr.ref]).

This seems to reinforce the decision of the working group.

The use of "use" should still be cross-referenced. The statements in 11.4.12 [class.nest] and 11.6 [class.local] should also be rewritten to state the requirement positively rather than negatively as the list of "can't"s is already missing some cases such as template parameters.

Notes from the 4/02 meeting:

We backed away from "use" in the technical sense, because the requirements on the form of reference are the same whether or not the reference occurs inside a sizeof.

Proposed Resolution (revised October 2002):

In 11.4 [class.mem] paragraph 9, replace

Except when used to form a pointer to member (7.6.2.2 [expr.unary.op]), when used in the body of a nonstatic member function of its class or of a class derived from its class (11.4.3 [class.mfct.non.static]), or when used in a mem-initializer for a constructor for its class or for a class derived from its class (11.9.3 [class.base.init]), a nonstatic data or function member of a class shall only be referred to with the class member access syntax (7.6.1.5 [expr.ref]).

with the following paragraph

Each occurrence in an expression of the name of a nonstatic data member or nonstatic member function of a class shall be expressed as a class member access (7.6.1.5 [expr.ref]), except when it appears in the formation of a pointer to member (7.6.2.2 [expr.unary.op]), when it appears in the body of a nonstatic member function of its class or of a class derived from its class (11.4.3 [class.mfct.non.static]), or when it appears in a mem-initializer for a constructor for its class or for a class derived from its class (11.9.3 [class.base.init]).

In 11.4.12 [class.nest] paragraph 1, replace the last sentence,

Except by using explicit pointers, references, and object names, declarations in a nested class can use only type names, static members, and enumerators from the enclosing class.

with the following

[Note: In accordance with 11.4 [class.mem], except by using explicit pointers, references, and object names, declarations in a nested class shall not use nonstatic data members or nonstatic member functions from the enclosing class. This restriction applies in all constructs including the operands of the sizeof operator.]

In the example following 11.4.12 [class.nest] paragraph 1, change the comment on the first statement of function f to emphasize that sizeof(x) is an error. The example reads in full:

  int x;
  int y;
  class enclose {
  public:
    int x;
    static int s;
    class inner {
      void f(int i)
      {
        int a = sizeof(x);  // error: direct use of enclose::x even in sizeof
        x = i;              // error: assign to enclose::x
        s = i;              // OK: assign to enclose::s
        ::x = i;            // OK: assign to global x
        y = i;              // OK: assign to global y
      }
      void g(enclose* p, int i)
      {
        p->x = i;        // OK: assign to enclose::x
      }
    };
  };

  inner* p = 0;             // error: inner not in scope



484. Can a base-specifier name a cv-qualified class type?

Section: 11.7  [class.derived]     Status: CD1     Submitter: Richard Corden     Date: 21 Oct 2004

[Voted into WP at the October, 2006 meeting.]

Issue 298, recently approved, affirms that cv-qualified class types can be used as nested-name-specifiers. Should the same be true for base-specifiers?

Rationale (April, 2005):

The resolution of issue 298 added new text to 11.3 [class.name] paragraph 5 making it clear that a typedef that names a cv-qualified class type is a class-name. Because the definition of base-specifier simply refers to class-name, it is already the case that cv-qualified class types are permitted as base-specifiers.

Additional notes (June, 2005):

It's not completely clear what it means to have a cv-qualified type as a base-specifier. The original proposed resolution for issue 298 said that “the cv-qualifiers are ignored,” but that wording is not in the resolution that was ultimately approved.

If the cv-qualifiers are not ignored, does that mean that the base-class subobject should be treated as always similarly cv-qualified, regardless of the cv-qualification of the derived-class lvalue used to access the base-class subobject? For instance:

    typedef struct B {
        void f();
        void f() const;
        int i;
    } const CB;

    struct D: CB { };

    void g(D* dp) {
        dp->f();    // which B::f?
        dp->i = 3;  // permitted?
    }

Proposed resolution (October, 2005):

  1. Change 11.3 [class.name] paragraph 5 as indicated:

  2. A typedef-name (9.2.4 [dcl.typedef]) that names a class type, or a cv-qualified version thereof, is also a class-name, but class-name. If a typedef-name that names a cv-qualified class type is used where a class-name is required, the cv-qualifiers are ignored. A typedef-name shall not be used as the identifier in a class-head.
  3. Delete 9.2.4 [dcl.typedef] paragraph 8:

  4. [Note: if the typedef-name is used where a class-name (or enum-name) is required, the program is ill-formed. For example,

        typedef struct {
            S();     // error: requires a return type because S is
                      // an ordinary member function, not a constructor
        } S;
    

    end note]




390. Pure virtual must be defined when implicitly called

Section: 11.7.4  [class.abstract]     Status: CD1     Submitter: Daniel Frey     Date: 14 Nov 2002

[Voted into WP at March 2004 meeting.]

In 11.7.4 [class.abstract] paragraph 2, it reads:

A pure virtual function need be defined only if explicitly called with the qualified-id syntax (_N4567_.5.1.1 [expr.prim.general]).

This is IMHO incomplete. A dtor is a function (well, a "special member function", but this also makes it a function, right?) but it is called implicitly and thus without a qualified-id syntax. Another alternative is that the pure virtual function is called directly or indirectly from the ctor. Thus the above sentence which specifies when a pure virtual function need be defined ("...only if...") needs to be extended:

A pure virtual function need be defined only if explicitly called with the qualified-id syntax (_N4567_.5.1.1 [expr.prim.general]) or if implicitly called (11.4.7 [class.dtor] or 11.9.5 [class.cdtor]).

Proposed resolution:

Change 11.7.4 [class.abstract] paragraph 2 from

A pure virtual function need be defined only if explicitly called with the qualified-id syntax (_N4567_.5.1.1 [expr.prim.general]).

to

A pure virtual function need be defined only if explicitly called with, or as if with (11.4.7 [class.dtor]), the qualified-id syntax (_N4567_.5.1.1 [expr.prim.general]).

Note: 11.4.7 [class.dtor] paragraph 6 defines the "as if" cited.




8. Access to template arguments used in a function return type and in the nested name specifier

Section: 11.8  [class.access]     Status: CD1     Submitter: Mike Ball     Date: unknown

[Moved to DR at 4/01 meeting.]

Consider the following example:

    class A {
       class A1{};
       static void func(A1, int);
       static void func(float, int);
       static const int garbconst = 3;
     public:
       template < class T, int i, void (*f)(T, int) > class int_temp {};
       template<> class int_temp<A1, 5, func> { void func1() };
       friend int_temp<A1, 5, func>::func1();
       int_temp<A1, 5, func>* func2();
   };
   A::int_temp<A::A1, A::garbconst + 2, &A::func>* A::func2() {...}
ISSUE 1:

In 11.8 [class.access] paragraph 5 we have:

This means, if we take the loosest possible definition of "access from a particular scope", that we have to save and check later the following names

      A::int_temp
      A::A1
      A::garbconst (part of an expression)
      A::func (after overloading is done)
I suspect that member templates were not really considered when this was written, and that it might have been written rather differently if they had been. Note that access to the template arguments is only legal because the class has been declared a friend, which is probably not what most programmers would expect.

Rationale:

Not a defect. This behavior is as intended.

ISSUE 2:

Now consider void A::int_temp<A::A1, A::garbconst + 2, &A::func>::func1() {...} By my reading of 11.8.8 [class.access.nest] , the references to A::A1, A::garbconst and A::func are now illegal, and there is no way to define this function outside of the class. Is there any need to do anything about either of these Issues?

Proposed resolution (04/01):

The resolution for this issue is contained in the resolution for issue 45.




494. Problems with the resolution of issue 45

Section: 11.8  [class.access]     Status: CD1     Submitter: Lloyd J. Lewins     Date: 17 Dec 2004

[Voted into WP at the October, 2006 meeting.]

The proposed resolution for issue 45 inserts the following sentence after 11.8 [class.access] paragraph 1:

A member of a class can also access all names as the class of which it is a member.

I don't think that this is correctly constructed English. I see two possibilities:

  1. This is a typo, and the correct change is:

    A member of a class can also access all names of the class of which it is a member.

  2. The intent is something more like:

    A member of a nested class can also access all names accessible by any other member of the class of which it is a member.

[Note: this was editorially corrected at the time defect resolutions were being incorporated into the Working Paper to read, “...can also access all the names declared in the class of which it is a member,” which is essentially the same as the preceding option 1.]

I would prefer to use the language proposed for 11.8.8 [class.access.nest]:

A nested class is a member and as such has the same access rights as any other member.

A second problem is with the text in 11.8.4 [class.friend] paragraph 2:

[Note: this means that access to private and protected names is also granted to member functions of the friend class (as if the functions were each friends) and to the static data member definitions of the friend class. Thi