Namespaces
Variants

std::future<T>:: get

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
Plantilla principal
T get ( ) ;
(1) (desde C++11)
std:: future < T & > Especializaciones
T & get ( ) ;
(2) (desde C++11)
std:: future < void > Especialización
void get ( ) ;
(3) (desde C++11)

La función miembro get espera (llamando a wait() ) hasta que el estado compartido esté listo, luego recupera el valor almacenado en el estado compartido (si existe). Inmediatamente después de llamar a esta función, valid() es false .

Si valid() es false antes de la llamada a esta función, el comportamiento es indefinido.

Contenidos

Valor de retorno

1) El valor v almacenado en el estado compartido, como std :: move ( v ) .
2) La referencia almacenada como valor en el estado compartido.
3) (ninguno)

Excepciones

Si una excepción fue almacenada en el estado compartido referenciado por el future (por ejemplo, mediante una llamada a std::promise::set_exception() ) entonces esa excepción será lanzada.

Notas

El estándar de C++ recomienda que las implementaciones detecten el caso cuando valid() es false antes de la llamada y lancen una std::future_error con una condición de error de std::future_errc::no_state .

Ejemplo

#include <chrono>
#include <future>
#include <iostream>
#include <string>
#include <thread>
std::string time()
{
    static auto start = std::chrono::steady_clock::now();
    std::chrono::duration<double> d = std::chrono::steady_clock::now() - start;
    return "[" + std::to_string(d.count()) + "s]";
}
int main()
{
    using namespace std::chrono_literals;
    {
        std::cout << time() << " launching thread\n";
        std::future<int> f = std::async(std::launch::async, []
        {
            std::this_thread::sleep_for(1s);
            return 7;
        });
        std::cout << time() << " waiting for the future, f.valid() = "
                  << f.valid() << '\n';
        int n = f.get();
        std::cout << time() << " f.get() returned " << n << ", f.valid() = "
                  << f.valid() << '\n';
    }
    {
        std::cout << time() << " launching thread\n";
        std::future<int> f = std::async(std::launch::async, []
        {
            std::this_thread::sleep_for(1s);
            return true ? throw std::runtime_error("7") : 7;
        });
        std::cout << time() << " waiting for the future, f.valid() = "
                  << f.valid() << '\n';
        try
        {
            int n = f.get();
            std::cout << time() << " f.get() returned " << n
                      << ", f.valid() = " << f.valid() << '\n';
        }
        catch (const std::exception& e)
        {
            std::cout << time() << " caught exception " << e.what()
                      << ", f.valid() = " << f.valid() << '\n';
        }
    }
}

Salida posible:

[0.000004s] launching thread
[0.000461s] waiting for the future, f.valid() = 1
[1.001156s] f.get() returned with 7, f.valid() = 0
[1.001192s] launching thread
[1.001275s] waiting for the future, f.valid() = 1
[2.002356s] caught exception 7, f.valid() = 0

Informes de defectos

Los siguientes informes de defectos que modifican el comportamiento se aplicaron retroactivamente a los estándares de C++ publicados anteriormente.

DR Applied to Behavior as published Correct behavior
LWG 2096 C++11 la sobrecarga (1) necesitaba verificar si T es MoveAssignable no requerido

Véase también

verifica si el futuro tiene un estado compartido
(función miembro pública)