【问题标题】:Inexplicable behaviour of the function accepting a universal reference and returning a const reference接受通用引用并返回 const 引用的函数的莫名行为
【发布时间】:2018-10-06 23:30:32
【问题描述】:

我一直认为下面这个接受通用引用的函数必须返回一个const-reference。

template <typename T>
const T& Const(T&& val)
{
    return val;
}

但是,以下代码使用 VS C++ 和 gcc 编译成功:

int x = 5;
Const(x) = 6;

运行后变量x的值等于6。因此,Const 函数返回一个非常量引用。

要获得编译器错误,必须修改函数 Const 以接受传统的左值引用或声明为返回 const std::remove_reference_t&lt;T&gt;&amp;。

这是为什么呢?我错过了什么规则? 提前致谢!

【问题讨论】:

    标签: c++ c++11 c++14


    【解决方案1】:

    通用参考

    不,它们被称为“转发引用”。 “通用参考”一词已被弃用。


    这是为什么呢?

    当你调用Const(x)时,x是一个左值,因此T被推导出为int&amp;。然后您的返回类型变为:

    • const T &amp; = T const &amp; -> int &amp; const &amp; -> int &amp;

    int &amp; const &amp; 是对const 的引用,对int 的引用与int&amp; 相同。 (在这种情况下,const 适用于int&amp;,而不仅仅是int,如T = int&amp;)。

    【讨论】:

    • 重新阅读您的答案才明白您的意思。看到const int &amp; &amp; 并解释说const 应用于int &amp; 有点误导。我可以建议写成const T &amp; = T const &amp; -> int &amp; const &amp; -> int &amp;吗?
    • East const 是最好的 const!
    • @Barry:显然不是,west const 让我 +100 代表!我爱西部 const。
    • 这是一个典型的例子,说明为什么左边的const (west const) 只是一个混淆的接收器。它不仅让 OP 感到困惑,解决它的人也搞砸了。
    • @JonKalb 他们可以。尼亚。
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多