C++ 如何让方法采用vector&&而不是vector?

C++ 如何让方法采用vector&&而不是vector?,c++,c++11,c++14,c++17,C++,C++11,C++14,C++17,我希望避免复制向量,而是使用右值引用。这些就是方法 bool GeckoChildProcessHost::SyncLaunch(std::vector<std::string> aExtraOpts, int aTimeoutMs) { if (!AsyncLaunch(std::move(aExtraOpts))) { return false; } return WaitUntilConnected(aTimeoutMs); } bool Gec

我希望避免复制向量,而是使用右值引用。这些就是方法

    bool GeckoChildProcessHost::SyncLaunch(std::vector<std::string> 
aExtraOpts, int aTimeoutMs) {
  if (!AsyncLaunch(std::move(aExtraOpts))) {
    return false;
  }
  return WaitUntilConnected(aTimeoutMs);
}

bool GeckoChildProcessHost::AsyncLaunch(std::vector<std::string> aExtraOpts) 
{
  PrepareLaunch();

#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
  if (IsMacSandboxLaunchEnabled()) {
    AppendMacSandboxParams(aExtraOpts);
  }
#endif

  MessageLoop* ioLoop = XRE_GetIOMessageLoop();

  MOZ_ASSERT(mHandlePromise == nullptr);
  mHandlePromise = new HandlePromise::Private(__func__);

  // Currently this can't fail (see the MOZ_ALWAYS_SUCCEEDS in
  // MessageLoop::PostTask_Helper), but in the future it possibly
  // could, in which case this method could return false.
  ioLoop->PostTask(NewNonOwningRunnableMethod<std::vector<std::string>>(
      "ipc::GeckoChildProcessHost::RunPerformAsyncLaunch", this,
      &GeckoChildProcessHost::RunPerformAsyncLaunch, aExtraOpts));

  return true;
}
我该怎么做?我还认为我需要改变他们的呼叫者以使用move。我该怎么做? 下面是其中一个调用方的代码

 bool GeckoChildProcessHost::LaunchAndWaitForProcessHandle( StringVector 
aExtraOpts) {
  if (!AsyncLaunch(std::move(aExtraOpts))) {
    return false;
  }

  MonitorAutoLock lock(mMonitor);
  while (mProcessState < PROCESS_CREATED) {
    lock.Wait();
  }
  MOZ_ASSERT(mProcessState == PROCESS_ERROR || mChildProcessHandle);

  return mProcessState < PROCESS_ERROR;
}
感谢您的帮助。谢谢

但是没有专门使用vector&&的地方。这基本上就是我想做的

你确定要这么做吗?这是你之前写的东西:

我想避免复制向量

如果我理解正确,你想移动向量,而不是复制它

问题是你现在做的每件事都是正确的。您不能自己使用右值引用来移动数据。事实上,对函数参数使用右值引用将阻止它通过引用而不是移动传递的移动。Rvalue引用用于实现移动语义。移动变量的真正目的是在通过值传递变量时使用std::move,从而导致移动,而您已经这样做了

请参见,将move和copy构造函数设置为在同一重载集中。在向其发送右值时,可以调用副本的优化版本。有时您仍然希望编译器选择优化的版本,因为您不关心变量会发生什么。函数std::move就是这样做的。只需将左值转换为右值。然后,move构造函数执行实际的移动

在代码中,您可以执行以下操作:

// no copy, even if AsyncLaunch is taking by
// value, since we 'move' into the value
!AsyncLaunch(std::move(aExtraOpts)) 

将aExtraOpts强制转换为右值,右值将数据移动到value参数中。如果函数通过引用或右值引用获取其参数,则根本不会移动,只需引用即可。

就您显示的代码而言,向量确实是移动的。还有其他要求吗?你的问题有意义吗?问问自己所引用字符串的生存期是多少?你怎么知道它们没有被摧毁?特别是如果他们是RHS临时人员。而向量最初会将字符串值复制到中,除非它们来自RHS临时变量-在这种情况下,它将移入;如果它必须重新分配自己,或者插入中间,那么这些字符串值会有效地移动。但是没有任何向量和具体使用。这基本上就是我想要做的。只有AsyncLaunch计划将aExtraOps转移到其他地方,如进入新的NowningRunnableMethod,才真正有意义通过值或右值引用获取aExtraOps。将它移到NewNon中并不是很有用,除非它反过来按值接受aExtraOps。如果您没有任何地方可以移动aExtraOps,只需通过常量引用即可。