jeudi 13 août 2020

Why is it illegal to bind an r-value to a const l-value reference in special member functions?

For function parameters, it is possible to bind an r-value to an l-value const reference. However, this does not seem to apply to special member function like the copy-constructor, and copy-assignment operator in C++11 and C++14. Is there a motivation for this?

When using C++17, it is possible to copy-construct, but not copy assign, from an r-value. Is there a motivation why only the behavior for the copy-constructor was changed here?

All of this is demonstrated in the following example:

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

void bar(B const &) {}

int main() {
    bar(B{}); // does work
    B(B{}); // only works in C++17

    B b{};
    b = B{}; // doesn't work
}

Aucun commentaire:

Enregistrer un commentaire