c++ - 重载指针的右值/常量左值

标签 c++ c++11 rvalue-reference

我正在使用 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)

Fixed version .

关于c++ - 重载指针的右值/常量左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789366/

相关文章:

c++ - 从抽象基类访问重载函数

c++ - std :move 的魔力是什么

c++ - 将右值引用传递给右值引用参数时发生错误

c++ - 析构函数隐藏在这段代码的什么地方?

c++ - Qt:如何将 GUI 元素的集合放入独立的子类中(使用单独的 *.ui 文件)

c++ - 完美转发到作为参数接收的 lambda

c++ - 从模板参数中获取函数参数

c++ - 检查一个 vector 是否包含另一个 vector 的子字符串

c++ - 用于 C++ 的快速、庞大且可扩展的几何库

c++ - 获取 btCollisionShape 当前变换