简体   繁体   English

C ++如何处理const double并引用int?

[英]How does C++ handle a const double& that refers to an int?

I was working on some template code this morning where I used a BOOST_STATIC_ASSERT to ensure I wasn't creating a reference to the wrong type, as I thought it might be a clearer error message. 我今天早上正在研究一些模板代码,我使用BOOST_STATIC_ASSERT来确保我没有创建对错误类型的引用,因为我认为这可能是一个更清晰的错误消息。 However when I tried removing the static assert to take a look at the alternative compiler error I was shocked to discover that gcc doesn't even complain when you try to make a const double& referring to an int: 但是,当我尝试删除静态断言以查看替代编译器错误时,我惊讶地发现,当您尝试使const为double并引用int时,gcc甚至不会抱怨:

#include <iostream>

int main()
{
    int x = 5;
    const double& y = x;
    std::cout << y << std::endl;

    return 0;
}

Compiles, and doesn't even warn: 编译,甚至不警告:

$ g++ ~/stuff/badRef.cpp -Wall -Wextra -pedantic
$ a.out
5

What's going on here? 这里发生了什么? Is this undefined behaviour? 这是未定义的行为吗? If so why doesn't gcc complain? 如果是这样,为什么gcc不抱怨? On my machine int is 4 bytes and a double is 8. That means that when printing a double& it should interpret 8 bytes at that address as a double and print it, yet there is actually a 4 byte int at that location. 在我的机器上int是4个字节而double是8.这意味着当打印double时它应该将该地址的8个字节解释为double并打印它,但实际上在该位置有4个字节的int。

Very confused. 非常困惑。 Help! 救命!

const double& y = x; creates a temporary double with the value static_cast<double>(x) , then binds that temporary to y . 使用值static_cast<double>(x)创建一个临时double ,然后将该临时值绑定到y The lifetime of the temporary is extended to match the lifetime of y . 临时的生命周期延长以匹配y的生命周期。

This is completely legal C++ (03 and 11), hence the lack of warning/error. 这是完全合法的C ++(03和11),因此缺少警告/错误。

it's well defined and legal. 它定义明确,合法。 y refers to a temporary. y指的是临时的。 consider also when you pass parameters: 传递参数时也要考虑:

void foo(const int& p);
foo(3.14);

Note also that this is not valid C++ if the reference is not const . 另请注意, 如果引用不是const ,则这不是有效的C ++。 VS 6 got that wrong and allowed binding a mutable reference to a temporary. VS 6得到了错误并允许将可变引用绑定到临时引用。 This applies only to const references. 这仅适用于const引用。

const T& can bind to a temporary, so x is being converted to double and the copy is bound to y . const T&可以绑定到临时,因此x被转换为double ,并且副本绑定到y If you check, you'll see that &x != &y . 如果你检查,你会看到&x != &y The reason for this behaviour is to allow passing literals to functions that take their parameters by const reference. 此行为的原因是允许将文字传递给通过const引用获取其参数的const

This is a good example for those who think that pointers and references are the same. 对于那些认为指针和引用相同的人来说,这是一个很好的例子。

double const*const y2 = &x;

gives
bad.cpp:7:30: error: cannot convert ‘int*’ to ‘const double* const’ in initialization

The reason it works for references is explained in the other posts. 它适用于参考的原因在其他帖子中有解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM