c++ - 这似乎是 clang++ 编译器中的一个错误

标签 c++ c++11 reference clang++

以下代码正常执行(参见 here ):

#include <iostream>

struct A {
    int i;
    A():i(1){}
    operator int&() { return i; }
};

int& rri = A();

int main()
{
    int& ri = A();
    std::cout << ri << '\n';
    std::cout << rri << '\n';
}

打印

1
1

如预期。但是,如果我注释掉 main() 中的前两个语句,只留下

std::cout << rri << '\n';

代码打印0

编辑:

让我们假设问题出在我的代码上。但后来我问:我在下面复制的标准 8.5.3/5 中的第三个要点的目的是什么:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

  • If the reference is an lvalue reference and the initializer expression

    • is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” or

    • has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be converted to an lvalue of type “cv3 T3,” where “cv1 T1” is reference-compatible with “cv3 T3” (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) and choosing the best one through overload resolution (13.3)),

    then the reference is bound to the initializer expression lvalue in the first case and to the lvalue result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object). [ Note: The usual lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not needed, and therefore are suppressed, when such direct bindings to lvalues are done. —end note ]

最佳答案

未定义的行为:rirri 都被初始化为引用临时对象的成员,该成员立即被销毁。

悬空引用指向一些可能被另一个对象重用的内存位,在这种情况下,您可能会看到来自该对象的数据。或者您可能会看到一些其他类型的未定义行为。

关于c++ - 这似乎是 clang++ 编译器中的一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21936668/

相关文章:

c++ - 如何在递归函数调用中返回当前函数值

c++ - 这种递减的顺序是否调用了未定义的行为?

c++ - 模板化枚举类运算符

c++ - 三元运算符在 `int` 和 `float` 上的结果

c++ - 删除临时指针时出现段错误

c++ - 包括类构造函数的方法链接

c++ - 从自由函数与成员函数返回仅移动类型

c# - 如何枚举给定根对象的所有可到达对象?

c++ - 为初始化引用实例变量的构造函数提供默认值

javascript - 这会复制对象还是添加对它的引用?