1

In class Pos the move constructor was defined as deleted.
Now function getPos() can't return a object?

Why it cannot use copy constructor to deal with the return value?

#include <iostream>

using namespace std;

#define debug(x) cout<<#x<<": "<<(x)<<endl;

class Pos {
public:
    Pos() { cout << "call:Pos()" << endl; }
    Pos(const Pos&p) { cout << "call:Pos(const Pos&p)" << endl; }
    Pos(Pos&& p) noexcept = delete;

    ~Pos() {
        cout << "call~Pos()" << endl;
    }
};

Pos getPos()
{
    Pos p;
    return p; // Error: cannot reference function (declared line number: 12) - it is a deleted function
}


int main() 
{
    Pos p = getPos();
    cin.get();
    return 0;
}
Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
Leon
  • 41
  • 7
  • @KonradRudolph I think GCC is compiling that erroneously. Clang still fails it: https://godbolt.org/. – NathanOliver Sep 27 '21 at 12:19
  • @NathanOliver Odd, GCC 11 also fails with `-std=c++20` (as well as pre-17 standards). Only C++17 works. I *thought* that C++17 was supposed to fix this behaviour but instead this looks like a very specific bug in GCC 11 when targeting C++17. What a shame — I feel that the GCC 11 behaviour for C++17 *should* be the correct one. – Konrad Rudolph Sep 27 '21 at 12:23
  • It's no defect. The move c'tor is decalred explicitly. NRVO is not guaranteed, so the chosen c'tor must be viable. A deleted definition is still a definition, so it's chosen and errors out. Common advice is to not explicitly delete move operations. Instead, the copy c'tor will supress the move operations, so they won't exist at all. – StoryTeller - Unslander Monica Sep 27 '21 at 12:28

0 Answers0