从右值对象获取无效引用时如何获得编译器警告?

时间:2018-07-02 23:10:33

标签: c++ compiler-warnings compiler-optimization

我最近在我们的代码库中找到了与该代码等效的代码:

#include <iostream>

struct A
{
    A(int a) : m_a(a) {}

    const int& a() const { return m_a; }
private:
    int m_a;
};

int main()
{
    int a = A(5).a(); // OK
    const int& a_ref = A(10).a(); // Not OK

    std::cout << "a=" << a << std::endl;
    std::cout << "a_ref=" << a_ref << std::endl;
}

使用g++ -std=c++11 -Wall -pedantic -Wextra test.cc运行此命令可获得输出(gcc版本5.4.0)

5
10

但是,添加-O3标志会得到结果

5
0

这很有意义,因为我们返回对m_a的引用,该引用属于右值A()。我最惊讶的是编译器没有对此抱怨。现在,我们通过提供两个版本的函数来解决该问题:

const int& a() & const { return m_a; }
int a() && const { return m_a; }

这可行,但是我有点担心代码中的其他地方可能存在类似的问题。 是否有任何我可以打开的编译器标志会对此发出警告?

0 个答案:

没有答案
相关问题