为什么通过条件操作员将参考传递到初始化列表会导致警告

Why does passing a reference through a conditional operator to an initializer list lead to a warning?

本文关键字:列表 初始化 警告 条件 操作员 参考 为什么      更新时间:2023-10-16

以下代码导致此警告(VC和GCC -WEXTRA):

warning C4413: 'ReferencingContainer::_vector' : reference member is initialized to a temporary that doesn't persist after the constructor exits

,但我不明白为什么。我以为我只是通过参考。

#include <vector>
struct Referencing
{
    Referencing(int const &x) : _x(x) {}
    Referencing(int const &x, int dummy) : _x(x > 5 ? x : throw "error") {} // bad code, warning is ok
    int const &_x;
};
struct Container
{
    std::vector<double> _vector;
};
struct ReferencingContainer
{
    ReferencingContainer(Container const &container)
        : _container(container)
        , _vector(container._vector.size() > 0 ? container._vector : throw "error")  // <-- warning occurs here
    {}
    Container const &_container;
    std::vector<double> const &_vector;
};
int main()
{
    Referencing test1(21);
    Referencing test2(22, 0);
    Container container;
    ReferencingContainer referencingContainer(container);
    return 0;
}

为什么编译器对我的代码不满意?我真的必须担心我的对象会引用临时性吗?

如果添加Wextra标志,您将获得此警告:

px.cpp:12:83: warning: a temporary bound to ‘ReferencingContainer::_vector’ only persists until the constructor exits [-Wextra]
         , _vector(container._vector.size() > 0 ? container._vector : throw "error") // <--- warning occurs here!

根据这个问题,这是编译器的错误:

关于临时临时构造成员构造成员

中的引用警告

但是,正如Vsoftco所指出的那样,警告在版本5.1

中持续存在。

其他相关问题:

  1. c 构造函数:垃圾,而const参考的初始化
  2. const参考是否会延长暂时的寿命?

一个可能的快速修复是将指针从?:表达式传递出来,然后解除它。

, _vector(*(container._vector.size() > 0 ? &container._vector : throw "error"))

那么,这里有什么问题?

编译器告诉您,通常他们对我们很有礼貌。由std :: vector ::大小的参考,我们有:

size_type size()const;

这意味着当您在行中调用它时会产生警告,size()将返回_vector大小的 copy 构造函数不超出范围。