c++ - 异步 C++11 中 future 的析构函数

标签 c++ gcc c++11

编译器不应该调用 future 的析构函数futuremain 之后完成,也就是说,不应该是函数 f()无论如何打电话? (gcc 4.7.2 不这样做)。

#include <iostream>
#include <thread>
#include <future>

using namespace std;

void f() {
    cout << "thread...\n";
}

int main() {
    auto future = async(&f);
    cout << "I am main\n";
}

编辑:我 Hello from main .正文thread...根本不打印。

编辑 2: future 调用的析构函数是否为 wait() ??

最佳答案

注意:下面的信息已过时(C++14 之前)。请参阅 Jonas 的回答以获取最新信息。


Should not a compiler call the destructor of the future future right after the main finishes

main 完成之前。但是是的。

that is, should not be the function f() called anyway?

没有,为什么?是什么让您认为 std::future 的析构函数会这样做?这不是析构函数的工作。事实上,根据§30.6.6/9,析构函数的唯一功能是释放 future 的共享状态并销毁*this。仅此而已。

关于c++ - 异步 C++11 中 future 的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635883/

相关文章:

c++ - 为什么在 C++ 20 中从标准库容器中删除了比较运算符?

c - C中同一函数的多个隐式声明

C++读取用户输入比较数组

c++ - 浮点提升 : stroustrup vs compiler - who is right?

c++ - 如何从 OpenGL 加载图像 BACK?

c++ - 没有在所有子类中使用虚函数的参数;有什么更好的设计方法吗?

android - NDK PIE 二进制文件在运行时显示链接器警告

c++ - 尝试理解传递给函数的参数(如果涉及一些算术运算)的评估

c++ - 调用线程会在 thread.join() 之后看到对局部变量的修改吗?

C++ 在函数的 .h 文件中重用相同的变量名(this.variable = variable error?)