如何让一种方法采用 vector&&<string>&而不是 vector<string>?

How to have a method take vector<string>&& instead of vector<string>?

本文关键字:gt vector lt string 方法 一种      更新时间:2023-10-16

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

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;
}

我该怎么做?另外,我相信我需要更改他们的呼叫者才能使用移动。我该怎么做? 下面是其中一个调用方的代码。

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,从而导致移动,您已经这样做了。

请参阅,移动和复制构造函数位于同一重载集中。有一个优化版本的"copy",可以在向其发送 rvalue 时调用。有时你仍然希望编译器选择优化版本,因为你不关心变量会发生什么。函数std::move做到这一点。只需将左值转换为右值即可。然后,移动构造函数执行实际移动。

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

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

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