我正在使用 gcc 4.8.4。
以下代码因第 22 行(指示)的编译器错误而失败:
invalid initialization of reference of type ‘int*&&’ from expression of type ‘int* const’
为什么不使用 square
的左值版本调用 square(ptr)
?
#include <iostream>
#include <memory>
int square(int* &&num) {
std::cout << "rvalue" << std::endl;
std::unique_ptr<int> x(num);
const auto ptr = x.get();
return square(ptr); // this is line 22
}
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;
}
最佳答案
您有订单问题:
return square(ptr);
只看到 int square(int* &&num)
声明并且无效
int square(const int* &num)
应该是 int square(int*const &num)
。
关于c++ - 重载指针的右值/常量左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789366/