尝试将 std::vector<std::p air<T, U>> 转换为其左值引用时收到 VS 编译器警告 C4239

Got VS compiler warning C4239 when trying to cast std::vector<std::pair<T, U>> to its lvalue ref

本文关键字:std lt gt 引用 VS 警告 编译器 C4239 vector air 转换      更新时间:2023-10-16

我有一个类Foo,其构造函数写成

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

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

Foo(std::vector<std::pair<int, char>>
{
{10, 'a'}
});

然后编译器给了我一个 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>> &'

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

提前谢谢。

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

考虑:

Foo::Foo(const std::vector<std::pair<int, char>> &Data)

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

在C++中,非常量引用可以绑定到左值,常量引用可以绑定到左值或右值,但没有任何东西可以绑定到非常量右值。这是为了防止人们改变临时值的值,这些临时值在使用新值之前就被销毁了。