Skip to content

Instantly share code, notes, and snippets.

@sithhell

sithhell/dangling_future.cpp Secret

Created Jan 13, 2015
Embed
What would you like to do?
// assume this brings in the stuff as outlined here:
// https://github.com/ned14/boost.spinlock/blob/expected_future/test_constexpr_future_promise2.cpp
#include <non_allocating_future_promise.hpp>
void work_with_future(future<int> f)
{
// Uh oh,
std::cout << "Got result: " << f.get() << "\n";
}
void dangling_reference_problem1
{
// This is our promise we use to set the result
promise<int> p;
future<int> f(p.get_future());
// Ok, now the promise p has a pointer to the future f, which is needed to
// set the result eventually.
std::vector<future<int> > fs;
fs.push_back(std::move(f));
// Uh oh. this function segfaults because the address of f isn't the same anymore!
p.set_value(42);
}
void do_some_work(promise<int> p)
{
// something that takes a while ...
p.set_value(42);
// p goes out of scope here ...
}
void dangling_reference_problem2
{
promise<int> p;
future<int> f(p.get_future());
std::thread t(do_some_work, std::move(p));
// The thread finished before we could retrieve the asynchronous result. Who
// kept it alive?
f.get()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.