Doc. no.: P0849R5
Date: 2020-10-30
Audience: EWG
Reply-to: Zhihao Yuan <zy at miator dot net>

auto(x): decay-copy in the language

Changes Since R4

Changes Since R3

Changes Since R2

Changes Since R1

Changes Since R0

Introduction

This paper proposes auto(x) and auto{x} for casting x into a prvalue as if passing x as a function argument by value. The functionality appears as the decay-copy function in the standard for exposition only.

Motivation

Obtaining a prvalue copy is necessary

A generic way to obtain a copy of an object in C++ is auto a = x; but such a copy is an lvalue. We could often convey the purpose in code more accurately if we can obtain the copy as a prvalue. In the following example, let Container be a concept,

void pop_front_alike(Container auto& x) {
    std::erase(x.begin(), x.end(), auto(x.front()));
}

If we wrote

void pop_front_alike(Container auto& x) {
    auto a = x.front();
    std::erase(x.begin(), x.end(), a);
}

, questions arise – why this is not equivalent to

void pop_front_alike(Container auto& x) {
    std::erase(x.begin(), x.end(), x.front());
}

The problem is, the statement to obtain an lvalue copy is a declaration:

    auto a = x.front();

The declaration’s primary purpose is to declare a variable, while the variable being a copy is the declaration’s property. In contrast, the expression to obtain an rvalue copy is a clear command to perform a copy:

    auto(x.front())

One might argue that the above is indifferent from

    T(x.front())

However, there are plenty of situations that the T is nontrivial to get. We probably don’t want to write the original example as

void pop_front_alike(Container auto& x) {
    using T = std::decay_t<decltype(x.front())>;
    std::erase(x.begin(), x.end(), T(x.front()));
}

Obtaining a prvalue copy with auto(x) works always

In standard library specification, we use the following exposition only function to fulfill auto(x)'s role:

template<class T>
constexpr decay_t<T> decay_copy(T&& v) noexcept(
    is_nothrow_convertible_v<T, decay_t<T>>) {
    return std::forward<T>(v);
}

This definition involves templates, dependent constexpr, forwarding reference, noexcept, and two traits, and still has caveats if people want to use it in practice. An obvious issue is that decay_copy(x.front()) copies x.front() even if x.front() is a prvalue, in other words, a copy.

There is a less obvious issue that needs a minimal reproduce:

class A {
    int x;

public:
    A();

    auto run() {
        f(A(*this));           // ok
        f(auto(*this));        // ok as proposed
        f(decay_copy(*this));  // ill-formed
    }

protected:
    A(const A&);
};

The problem is that decay_copy is nobody’s friend. We can use A directly in this specific example. However, in a more general setting, where a type has access to a set of type T's private or protected copy/move constructors, decay-copy an object of T fails inside that type’s class scope, but auto(x) continues to work.

Discussion

auto(x) is a missing piece

Replacing the char in char('a') with auto, we obtain auto('a'), which is a function-style cast. Such a formula also supports injected-class-names and class template argument deduction in C++17. Introducing auto(x) and auto{x} significantly improves the language consistency:

variable definition function-style cast new expression
auto v(x); auto(x) new auto(x)
auto v{x}; auto{x} new auto{x}
ClassTemplate v(x); ClassTemplate(x) new ClassTemplate(x)
ClassTemplate v{x}; ClassTemplate{x} new ClassTemplate{x}

** The type of x is a specialization of ClassTemplate.

With this proposal, all the cells in the table copy construct form x (due to CTAD’s default behavior) to obtain lvalues, prvalues, and pointers to objects, categorized by their columns. Defining auto(x) as a library[1] facility loses orthogonality.

Introducing auto(x) into the language even improves the library consistency:

type function style expression style
void_t<decltype(expr)> decltype(void(expr))
decay_t<decltype(expr)> decltype(auto(expr))

Do we also miss decltype(auto){x}?

decltype(auto){arg} can forward arg without computing arg's type. It is equivalent to static_cast<decltype(arg)>(arg) . If arg is a variable of type T&&, arg is an lvalue but static_cast<T&&>(arg) is an xvalue.

EWG discussed this idea, disliked its expert-friendly nature, and concluded that adding this facility would cause the teaching effort to add up.

Does auto works in place of decay-copy in the library specification?

Not as a simple find-and-replace, but can be made to improve the quality of the library specification.

The background is that, despite being exposition-only, decay-copy always materializes its argument and produces a copy. auto(expr) is a no-op if the expr is a prvalue.

In the library specification where uses decay-copy, some do not mean to materialize the expressions; some want a new copy; some do not care. However, with auto(x) semantics, we should distinguish the different needs and explicitly say so when a copy is needed.

Demo

Prevent algorithm from modifying through aliases: https://godbolt.miator.net/z/hhcvbc

Using auto(x) in rvalue fluent interface: https://godbolt.miator.net/z/TY8sxr

How auto(x) assists in defining concepts: https://godbolt.miator.net/z/GTaaeE

Compare diagnosis to new auto(x): https://godbolt.miator.net/z/Ks43an

Wording

The wording is relative to N4868.

Part 1

Modify 7.6.1.4 [expr.type.conv]/1 as indicated:

A simple-type-specifier (9.2.9.3) or typename-specifier (13.8) followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer. If the type is a placeholder for a deduced class type, it is replaced by the return type of the function selected by overload resolution for class template deduction (12.4.2.9) for the remainder of this section. Otherwise, if the type is auto, it is replaced by the type deduced for the variable x in the invented declaration ([dcl.spec.auto]):

    auto x init;

, where init is the initializer.

Modify 9.2.9.6 [dcl.spec.auto]/5 as indicated:

A placeholder type can also be used in the type-specifier-seq in the new-type-id or type-id of a new-expression (7.6.2.8) and as a decl-specifier of the parameter-declaration’s decl-specifier-seq in a template-parameter (13.2). The auto type-specifier can also be used as the simple-type-specifier in an explicit type conversion (functional notation) ([expr.type.conv]).

Part 2

Modify 24.3.2 [range.access.begin]/2 as indicated:

Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then:

Modify 24.3.3 [range.access.end]/2 as indicated:

Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then:

Modify 24.3.6 [range.access.rbegin]/2 as indicated:

Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then:

Modify 24.3.7 [range.access.rend]/2 as indicated:

Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then:

Modify 24.3.10 [range.prim.size]/2 as indicated:

Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then:

Modify 24.3.13 [range.prim.data]/2 as indicated:

Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then:

Modify 24.7.4.1 [range.all.general]/2 as indicated:

The name views::all denotes a range adaptor object (24.7.2). Given a subexpression E, the expression views::all(E) is expression-equivalent to:

[Drafting note: We could replace this use of decay-copy(E) (along with the other two in [range.take] and [range.drop]) with auto(identity()(E)), but it doesn’t seem to be an improvement. –end note]

Modify 32.4.3.3 [thread.thread.constr]/6 as indicated:

Effects: The new thread of execution executes

  invoke(decay-copyauto(std::forward<F>(f)),
   decay-copyauto(std::forward<Args>>(args))…)

with the calls to decay-copy being evaluatedvalues produced by auto being materialized ([conv.rval]) in the constructing thread. Any return value from this invocation is ignored. […]

Modify 32.4.4.2 [thread.jthread.cons]/6 as indicated:

Effects: Initializes ssource. The new thread of execution executes

  invoke(decay-copyauto(std::forward<F>(f)), get_stop_token(),
   decay-copyauto(std::forward<Args>>(args))…)

if that expression is well-formed, otherwise

  invoke(decay-copyauto(std::forward<F>(f)),
   decay-copyauto(std::forward<Args>>(args))…)

with the calls to decay-copy being evaluatedvalues produced by auto being materialized ([conv.rval]) in the constructing thread. Any return value from this invocation is ignored. […]

Modify 32.9.9 [futures.async]/4 as indicated:

Effects: The first function behaves the same as a call to the second function with a policy argument of launch::async | launch::deferred […]:

Modify 17.11.6 [cmp.alg] as indicated:

[Drafting note: This section proposes a resolution for LWG 3491[2]. –end note]

The name strong_order denotes a customization point object (16.3.3.3.6). Given subexpressions E and F, the expression strong_order(E, F) is expression-equivalent (3.21) to the following:

The name weak_order denotes a customization point object (16.3.3.3.6). Given subexpressions E and F, the expression weak_order(E, F) is expression-equivalent (3.21) to the following:

The name partial_order denotes a customization point object (16.3.3.3.6). Given subexpressions E and F, the expression partial_order(E, F) is expression-equivalent (3.21) to the following:

The name compare_strong_order_fallback denotes a customization point object (16.3.3.3.6). Given subexpressions E and F, the expression compare_strong_order_fallback(E, F) is expression-equivalent (3.21) to the following:

The name compare_weak_order_fallback denotes a customization point object (16.3.3.3.6). Given subexpressions E and F, the expression compare_weak_order_fallback(E, F) is expression-equivalent (3.21) to the following:

The name compare_partial_order_fallback denotes a customization point object (16.3.3.3.6). Given subexpressions E and F, the expression compare_partial_order_fallback(E, F) is expression-equivalent (3.21) to the following:

Acknowledgments

Thank Alisdair Meredith, Arthur O’Dwyer, and Billy O’Neal for providing examples and feedback for this paper. Thank James Touton for presenting the paper and bringing it forward. Thank Jens Maurer and Casey Carter for reviewing the wording.

References


  1. Krügler, Daniel. P0758R0 Implicit conversion traits and utility functions. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0758r0.html ↩︎

  2. Meredith, Alisdair. LWG 3491 What is a “decayed type?” https://cplusplus.github.io/LWG/issue3491 ↩︎