我GCC 4.4.7
发生此问题,特别是g++ 4.4.7 20120313 (Red Hat 4.4.7-17)
。我在clang 3.8
和GCC 4.8.4
下都尝试过,但没有遇到同样的问题。 Boost版本为boost 1.55
。最小的例子:
#include <iostream>
#include <boost/optional.hpp>
struct baz
{
boost::optional<int> x;
boost::optional<int> foo()
{
//If x is a local variable, the correct result is printed in main.
x = 25;
return x;
}
};
int main()
{
baz b{{}};
int t = 9999;
if (b.foo()) {
std::cout << "optional has value\n"; //Prints "optional has value" as expected
}
std::cout << b.foo().is_initialized() << "\n"; //Prints 1 as expected
t = *(b.foo());
std::cout << "t: " << t << "\n"; //Prints 0, expected 25
std::cout << *b.foo() << "\n"; //Prints 0, expected 25
std::cout << b.foo().get() << "\n"; //Prints 0, expected 25
//For all of the above, minor code changes lead to
//seemingly random differences in the results that are printed.
//For example:
//If this is uncommented, '25' is printed everywhere above, as expected:
//std::cout << b.foo().get_ptr() << "\n";
}
这是汇编为g++ example.cpp -std=c++0x -Wall -Wextra -O2 -o bot
(请注意,它在-O3
下也失败了,但不在O0
或O1
下。
这是否可能是由严格的别名问题引起的?或者还有其他事情发生在这里我不见了?
编辑:
Wandbox上的runnable example。