jeudi 4 mai 2017

Overloading rvalue/const lvalue for pointer

Why does the following code fail with error: invalid initialization of reference of type ‘int*&&’ from expression of type ‘int* const’? That is, why isn't the call to square(ptr) using the lvalue version of square? I'm using gcc 4.8.4.

int square(int* &&num) {
    std::cout << "rvalue" << std::endl;
    std::unique_ptr<int> x(num);
    const auto ptr = x.get();
    return square(ptr);
}

int square(const int* &num) {
    std::cout << "lvalue" << std::endl;
    return (*num) * (*num);
}

int main() {
    std::unique_ptr<int> up(new int);
    *up = 5;
    std::cout << square(up.release()) << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire