You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将const T*&&绑定到T*类型xvalue?Clang与GCC谁的实现正确?

右值引用绑定的编译器行为正确性辨析
int* p;
const int*&& r = static_cast<int*&&>(p);

注:const int*&&是指向const int的指针的右值引用。

不同编译器的行为表现

  • Clang编译结果:可正常编译,r绑定到临时对象,对应汇编代码显示:

    p: .quad   0
    r: .quad   _ZGR1r_ // r is a reference to a temporary object, otherwise this would be p
    
  • GCC编译结果:拒绝编译,报错信息如下:

    <source>:2:18: error: binding reference of type 'const int*&&' to 'int*' discards qualifiers
        2 | const int *&&r = static_cast<int*&&>(p);
          |                  ^~~~~~~~~~~~~~~~~~~~~~
    

核心疑问

个人认为GCC正确实现了CWG 2352对[dcl.init.ref] p4的修改,但不确定理解是否正确。请问哪款编译器的实现是正确的?

注:本问题示例灵感来自CWG 2018中提及的最后一行代码。
注:若允许将const int*&&绑定到int*&&,会引发const正确性陷阱,这与将int**转换为const int**的问题类似。个人认为委员会不太可能允许此类引用绑定,但缺陷报告的措辞仍可能允许该操作。

内容的提问来源于stack exchange,提问作者Jan Schultke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:35:09