注册 | 登录


sinat_29174099 2016-07-22



up vote 1 down vote favorite

I want to run some system calls in parallel, but even if I call f1.get() the coping in the lines below does not take place. What is wrong with this code?

auto f1 = std::async( system, string("cp a b").c_str() );
f1.get(); // there is still no file "b".

Note: I wrote string(...).c_str() because in my real code I'm using putting the argument together from different strings.

c++ c++11 asynchronous future share | improve this question edited Apr 24 '16 at 12:38 BoundaryImposition 231k 40 359 622 asked Apr 24 '16 at 12:12 dani 594 6 20 3   string("cp a b").c_str() will pass a dangling pointer to system when it is run. –  melak47 Apr 24 '16 at 12:14      On the other hand, string literals stay alive. std::async( system, "cp a b") –  Buella Gábor Apr 24 '16 at 12:19      And the code seems to work. Perhaps there are a few problems with the way arguments to system are constructed. –  Buella Gábor Apr 24 '16 at 12:22 2   Please, do not enter the solution inside your question, but post an answer and accept it. –  Rafał Rawicki Apr 24 '16 at 12:32 add a comment  | 

1 Answer 1

active oldest votes up vote 2 down vote accepted

The std::string containing your command is a temporary object and will only live until the end of the std::async call, so by the time system is called, the pointer may refer to deleted memory, which may happen to work, or it might read rm -rf / --no-preserve-root - it's undefined behavior.

You need to ensure the string object lives long enough. In your example that is easy enough, but it's not always so if you're launching asynchronous operations.

C++11 lambda expressions give us a nice way store the string for exactly as long as we need it:

相关推荐:Android 自定义主菜单


std::string command = "cp main.cpp b";

auto f1 = std::async(std::launch::async, 
    [command]{ // copy command into the closure

Also, note that you didn't request the async launch policy, so your function may execute synchronously still.

Side note: You may want to consider using something like POCO's Process if you're launching external processes and want to capture output, exit status and so on.

share | improve this answer answered Apr 24 '16 at 12:49 melak47 3,674 1 12 27 add a comment  | 

Your Answer

  draft saved draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name Email

Post as a guest

Name Email discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged c++ c++11 asynchronous future or ask your own question.

相关推荐:修改自定义数据类型精度 - zjcxc(邹建)的Blog

/*--修改自定义数据类型精度的示例 自定义数据类型一旦被引用,就不能再修改和删除,如果要修改数据的精度,就非常麻烦,下面的示例演示了如何修改

自定义开关控件 Android自定义控件一般有三种方式 1、继承Android固有的控件,在Android原生控件的基础上,进行添加功能和逻辑。 2、继承ViewGroup,这类自定义控件是可以往自己的布局里面...










您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱