【问题标题】:non standard extension warning when searching in a vector of unique_ptrs在 unique_ptrs 向量中搜索时出现非标准扩展警告
【发布时间】:2016-02-25 22:22:49
【问题描述】:

在下面的代码sn-p中:

std::vector<std::unique_ptr<int>> vec;
vec.emplace_back(std::make_unique<int>(1));
vec.emplace_back(std::make_unique<int>(2));
vec.emplace_back(std::make_unique<int>(3));
vec.emplace_back(std::make_unique<int>(4));
vec.emplace_back(std::make_unique<int>(5));
auto & itr = std::find_if(vec.begin(), vec.end(), [](std::unique_ptr<int> & val)->bool
{
   return *val == 5;
});
vec.erase(itr);

我收到以下警告:

Severity    Code    Description Project File    Line
Warning C4239   nonstandard extension used: 'initializing': conversion from 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<std::unique_ptr<int,std::default_delete<_Ty>>>>>' to 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<std::unique_ptr<int,std::default_delete<_Ty>>>>> &'

我做错了什么?

我在 VS2015 上,此警告仅在警告级别 4 出现。我应该忽略它还是会导致任何偷偷摸摸的问题(如果在更大的上下文中使用了涉及 unique_ptrs 向量的类似代码)?

【问题讨论】:

    标签: c++ c++11 vector compiler-warnings unique-ptr


    【解决方案1】:

    find_if 将迭代器按值返回到匹配元素,并且您试图将其绑定到非常量引用,这是非法的。 VC++ 编译器有一个臭名昭著的扩展允许这样做,但幸运的是当你设置/W4 时会生成一个警告。将您的代码更改为

    auto itr = std::find_if(...);
    

    【讨论】:

    • 这是一个虚假的警告。我在将 lambda 分配给左值 ref 类型变量时得到它。您认为我们应该将其视为错误并符合跨平台和标准吗?
    • @Nik-Lz 如果您的意思是像auto&amp; l = []{}; 这样的代码,那不是虚假警告,该代码是非法的。您应该将 C4239 变为错误或使用 /permissive- 编译,这将拒绝代码。
    【解决方案2】:

    从 find_if 返回时,您通过非常量引用获取临时引用。

    随便

    auto itr = ... ;
    

    const auto& itr =  ... ;
    

    【讨论】:

    • auto&amp;&amp; itr = ... ;,如果我们正在玩绑定到引用游戏。
    猜你喜欢
    • 2012-09-12
    • 2013-08-24
    • 2011-07-26
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    相关资源
    最近更新 更多