我发现最令人讨厌的绑定问题似乎是GCC特有的。我不确定这是否是我不了解const auto&
绑定的规则,还是问题出在gcc编译器特定的错误。相比之下,Visual Studio 2015的C ++编译器(在撰写本文时为Update 2)不会表现出这种不可预测的行为。我能够用简约的live coliru demo重现问题。
如果将自动变量绑定到“ const auto&”,则会出现问题。在这种情况下,const auto&
绑定变量似乎绑定到垃圾。如果这是用户错误(我不理解规则),那么有人可以解释有关如何避免这种意外行为的规则。现场演示显示了我遇到错误的示例,我不确定在其他地方是否可能出现此问题,因为我倾向于尽可能使用const auto&
绑定。
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
引用可以延长其绑定到的临时目录的寿命。但是,这仅在直接绑定临时目录时有效:
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/