Incorrect results when raising dereferencing :: optionally directly from return value

This problem occurs for me on GCC 4.4.7

, in particular g++ 4.4.7 20120313 (Red Hat 4.4.7-17)

. I tried it under clang 3.8

and GCC 4.8.4

and didn't have the same problem. Boost version boost 1.55

. Minimal example:

#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";
}

      

This is compiled as g++ example.cpp -std=c++0x -Wall -Wextra -O2 -o bot

(note that it also fails under -O3

, but not under O0

or O1

).

Is it possible that this is caused by a strict alias problem? Or is there something else going on here I'm missing?

Edit:

A runnable example in Wandbox.

+3


source to share





All Articles