尝试将 std::vector<std::pair<T, U>> 转换为其左值引用时出现 VS 编译器警告 C4239

use*_*342 1 c++ visual-c++ c++11 c++14

我有一个类Foo,其构造函数是这样写的

Foo::Foo(std::vector<std::pair<int, char>> &Data)
    : //Initialization list
{
    //Some other initialization
}
Run Code Online (Sandbox Code Playgroud)

我尝试在我的代码中调用它

Foo(std::vector<std::pair<int, char>>
    {
        {10, 'a'}
    });
Run Code Online (Sandbox Code Playgroud)

然后编译器给我一个 C4239 说

nonstandard extension used: 'argument': conversion from 
'std::vector<std::pair<int,char>,std::allocator<_Ty>>' to 
'std::vector<std::pair<int,char>,std::allocator<_Ty>> &'
Run Code Online (Sandbox Code Playgroud)

我理解该消息,但为什么编译器对这种转换不满意?

提前致谢。

Ale*_*exD 5

您正在尝试将临时引用绑定到非常量引用。

考虑:

Foo::Foo(const std::vector<std::pair<int, char>> &Data)
Run Code Online (Sandbox Code Playgroud)

根据 Bjarne Stroustrup 的C++11 - 新的 ISO C++ 标准(强调我的):

在 C++ 中,非常量引用可以绑定到左值,常量引用可以绑定到左值或右值,但没有任何东西可以绑定到非常量右值。这是为了保护人们免于更改在使用新值之前被破坏的临时值的值。