c++ - 为什么通过条件运算符将引用传递给初始化列表会导致警告?

标签 c++ visual-c++

以下代码导致此警告(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!

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

Spurious warning about binding temporary to reference member in constructor

但是,正如 vsoftco 指出的那样,该警告在 5.1 版中仍然存在

其他相关问题:

  1. C++ constructor: garbage while initialization of const reference
  2. Does a const reference prolong the life of a temporary?

一个可能的快速修复是从 ?: 表达式中传递一个指针,然后取消引用它。

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

那么这里有什么问题呢?

编译器告诉你,通常他们对我们很有礼貌。引用 std::vector::size ,我们有:

size_type size() const;

这意味着当您在它创建警告的行中调用它时,size() 将返回大小为的拷贝 _vector,当构造函数超出范围时,它将超出范围。

关于c++ - 为什么通过条件运算符将引用传递给初始化列表会导致警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035621/

相关文章:

c++ - 当类版本可用时引用全局运算符delete[]

c++ - 程序结构

visual-c++ - 基本代码布局问题

C++ malloc.c :2905: __libc_malloc: Assertion

c++ - std::bind 分配给 std::function

c++ - Visual Studio 不保存启动项目和解决方案配置

c++ - VeriFone 终端应用程序可以通过以太网进行通信,还可以存储本地数据吗?

c++ - Visual Studio 2008 c++ 条件模板继承错误?

c++ - Linux、C++、第三方库

c++ - 纯碱基变化