代码之家  ›  专栏  ›  技术社区  ›  Navaneeth K N

临时绑定到左值引用

  •  9
  • Navaneeth K N  · 技术社区  · 15 年前

    我有以下代码

    string three()
    {
        return "three";
    }
    
    void mutate(string& ref)
    {
    }
    
    int main()
    {
        mutate(three()); 
        return 0;
    }
    

    你可以看到我路过 三() 突变 方法。这段代码编译得很好。我的理解是,临时文件不能分配给非常量引用。如果是,这个程序是如何编译的?

    有什么想法吗?

    编辑:

    编译器尝试过:vs 2008和vs2010 beta

    5 回复  |  直到 15 年前
        1
  •  8
  •   Naveen    15 年前

    它以前是在VC6编译器中编译的,所以我想为了保持向后兼容性,VS2008支持这个非标准扩展。尝试用 /Za (禁用语言扩展)标志,则应收到错误。

        2
  •  4
  •   yoco    15 年前

    这是VC++的邪恶延伸。如果使用/w4进行编译,编译器将警告您。我想你在读 Rvalue References: C++0x Features in VC10, Part 2 .本文还提到了这个问题。

        3
  •  3
  •   QbProg    15 年前

    这是微软的一个扩展,模仿许多其他微软编译器的行为。如果启用W4警告,将看到警告。

        4
  •  1
  •   Warren Young    15 年前

    编译,至少使用G++4:

    foo.cpp: In function ‘int main()’:
    foo.cpp:16: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’
    foo.cpp:10: error: in passing argument 1 of ‘void mutate(std::string&)’
    

    (由于我必须添加include和'using'行,因此行数被取消了3或4。)

    所以,您的编译器似乎没有它应该的那么严格。

        5
  •  0
  •   Adis H    15 年前

    我想这取决于编译器。G++4.1.2给了我这个。

    In function 'int main()':
    Line 15: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'std::string'
    compilation terminated due to -Wfatal-errors.
    

    可能是因为你什么都没做,所以电话被优化了。