dimanche 6 décembre 2015

vector of std::promise throws exception but boost::promise does not

Question : What is the proper way to store a collection of promises given out ?

I am using g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4 with "-std=c++11"

The following code throws an exception when the promise.set_value() is called. Message is "terminate called after throwing an instance of 'std::system_error' what(): Unknown error -1 Aborted (core dumped)"

#include <vector>
#include <future>

main()
{
    {   
        std::vector<std::promise<int>> q;
        std::promise<int> p;
        auto f = p.get_future();
        q.push_back(std::move(p));
        auto t1 = std::move(q.front());
        t1.set_value(10);
    }   
}

If I replace the std::promise with a boost::promise, it works

#include <vector>
#include <boost/thread/future.hpp>

main()
{
    {   
        std::vector<boost::promise<int>> q;
        boost::promise<int> p;
        auto f = p.get_future();
        q.push_back(std::move(p));
        auto t1 = std::move(q.front());
        t1.set_value(10);
    }   
}

What is most surprising is that the std::promise::set_value() does not throw an exception (or maybe gets caught somewhere?) if I just retain a declaration of the boost::promise in the program !

#include <vector>
#include <future>
#include <boost/thread/future.hpp>

main()
{
    {   // this hides the exception thrown by promise::set_value()
        boost::promise<int> p;
    }   

    {   
        std::vector<std::promise<int>> q;
        std::promise<int> p;
        auto f = p.get_future();
        q.push_back(std::move(p));
        auto t1 = std::move(q.front());
        t1.set_value(10);
    }   
}

Aucun commentaire:

Enregistrer un commentaire