直接从返回值解除引用boost :: optional时的结果不正确

时间:2017-03-29 05:12:33

标签: c++ c++11 gcc boost

GCC 4.4.7发生此问题,特别是g++ 4.4.7 20120313 (Red Hat 4.4.7-17)。我在clang 3.8GCC 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下也失败了,但不在O0O1下。

这是否可能是由严格的别名问题引起的?或者还有其他事情发生在这里我不见了?

编辑:

Wandbox上的runnable example

0 个答案:

没有答案