我发现最烦人的绑定(bind)问题似乎是特定于 GCC 的。我不确定这是不是我不理解 const auto&
绑定(bind)的规则,或者问题是否指向 gcc 编译器特定的错误。相比之下,Visual Studio 2015 的 C++ 编译器(撰写本文时的更新 2)没有表现出这种不可预测的行为。我能够用简约的方式重现问题 live coliru demo .
如果我将自动变量绑定(bind)到“const auto&”,就会出现问题。在这种情况下,const auto&
绑定(bind)变量似乎绑定(bind)到垃圾。如果这是用户错误(我不理解规则),有人可以解释有关我应该如何执行此操作以避免此类意外行为的规则。现场演示显示了我遇到错误的示例,我不确定这个问题是否可能发生在其他地方,因为我倾向于尽可能使用 const auto&
绑定(bind)。
OptPairWrapper wrapper;
wrapper.setOptPair(std::make_pair(1,2));
const auto& badConstAutoRefBind = wrapper.getOptPair().get();
const auto goodConstAutoBind = wrapper.getOptPair().get();
// This line prints garbage
std::cout << badConstAutoRefBind << std::endl;
// This line predictably prints (1,2)
std::cout << goodConstAutoBind << std::endl;
产生了以下输出
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp -lrt && ./a.out
(32767, 0)
(1, 2)
最佳答案
这与auto
无关.
const
引用可以延长它们所绑定(bind)的临时对象的生命周期。但是,这仅在直接绑定(bind)临时对象时有效:
int foo() { ... }
int main() {
int const &i = foo(); // Fine
}
在您的示例中,您调用 boost::optional<...>
的 get()
函数,它返回一个左值引用。此引用不是临时的,因此不会延长生命周期。
关于c++ - gcc 4.9.1 将 c++ 局部变量绑定(bind)到 const auto ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36576690/