Tasos Vogiatzoglou
Tasos Vogiatzoglou

Reputation: 2453

No state error in C++ 11 futures/promises

I am a bit confused about the behavior of futures/promises in C++.

The code is the following

 std::future<std::string> method() {
        std::promise<std::string> pr;
        std::future<std::string> ft = pr.get_future();

        std::thread t(                   
            [](std::promise<std::string> p)  
            {                      
                p.set_value("z");  
            },                     
            std::move(pr)          
        );                       
        t.detach();                    

        return std::move(ft);          
 }

When I run the code, there is an exception __throw_future_error((int)future_errc::no_state); thrown at std::future<std::string> ft = pr.get_future();

Any idea why is this happening ?

EDIT:

So, I have a minimal example that showcases the problem. Coliru (with g++ 4.8 and a bit newer stdlib) somehow seems to run it fine, but when it comes to my workstation it fails.

http://coliru.stacked-crooked.com/a/711e182594cbe7d3

I am compiling with

# gcc 4.7.3
g++ -g -std=c++11 -lpthread t.cpp -o t 

and

# clang 3.2.1
clang++ -g -std=c++11 -lpthread t.cpp -o t

libstdc++ version is 3.4.17

Workstation is a Linux Mint 15

Upvotes: 3

Views: 2711

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 218700

This looks like a bug. The default constructor of promise is specified to construct a shared state for the promise. The future returned from pr.get_future() should refer to that shared state.

Is -stdlib=libc++ an option for you?

Upvotes: 1

Related Questions