Is it safe to make a const reference member to a temporary variable?

前端 未结 6 1841
太阳男子
太阳男子 2021-01-13 09:32

I\'ve tried to code like this several times:

struct Foo
{
    double const& f;
    Foo(double const& fx) : f(fx)
    {
        printf(\"%f %f\\n\", f         


        
6条回答
  •  余生分开走
    2021-01-13 10:01

    If the temporary variable exists at the point where the reference is used, then the behavior is well defined. And in this case this temporary variable exists exactly because it is referenced! Form C++11 standard section 12.2.5:

    The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference ...

    Yes, the word hidden by '...' is the "except" and multiple exceptions are listed there, but none of them are applicable in this example case. So this is legal and well defined, should produce no warnings, but not very widely known corner case.

提交回复
热议问题