gpt4 book ai didi

c++ - clang & gcc 以不同的方式解释 cast 系列

转载 作者:行者123 更新时间:2023-11-30 04:51:30 24 4
gpt4 key购买 nike

以下内容:

#include <iostream>

int& addone(int& r) {
return ++r;
}

int main() {
std::cout << addone((int&)(int&&)7) << std::endl;
}

编译、运行并打印 8,使用 clang,甚至使用 -Wall -Wextra -Werror -pedantic 。
但是,使用 gcc 时,它根本无法编译,即使使用 -fpermissive 也是如此。

这里哪个是正确的? (最好有引号)

clang 结果 here , gcc 结果 here

最佳答案

看来第一次转换就OK了。您将整数文字 - 纯右值 - 转换为右值引用。这会导致临时物化转换:

[conv.rval] A prvalue of type T can be converted to an xvalue of type T.This conversion initializes a temporary object ([class.temporary]) of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object.

让我们考虑转换为左值引用:

[dcl.init.ref] 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 (does not apply, the expression is not an lvalue)

  • has a class type (does not apply, the type is int&&)

Otherwise, if the reference is an lvalue reference to a type that is not const-qualified or is volatile-qualified, the program is ill-formed. (applies)

看来程序的格式不正确。缺少来自 clang 的诊断表明存在编译器错误。

关于c++ - clang & gcc 以不同的方式解释 cast 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54763490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com