在C++ 14中,为什么lambda函数带有推导的返回类型默认情况下从返回类型中删除引用?IIUC,因为C++ 14 lambda函数具有推导的返回类型(没有显式的尾随返回类型)具有返回类型auto,它会丢弃引用(以及其他内容).
为什么做出这个决定?在我看来,当你的返回语句返回时,就像删除引用一样.
这种行为给我带来了以下令人讨厌的错误:
class Int {
public:
Int(int i) : m_int{i} {}
int m_int;
};
class C {
public:
C(Int obj) : m_obj{obj} {}
const auto& getObj() { return m_obj; }
Int m_obj;
};
class D {
public:
D(std::function<const Int&()> f) : m_f{f} {}
std::function<const Int&()> m_f;
};
Int myint{5};
C c{myint};
D d{ [&c](){ return c.getObj(); } } // The deduced return type of the lambda is Int (with no reference)
const Int& myref …Run Code Online (Sandbox Code Playgroud)