我想避免使用vector的副本,而是使用rvalue引用。这些是方法。
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
,从而导致移动,这是你已经做过的。
请参阅,move和copy构造函数位于同一个重载集中。有一个优化版本的“复制”,可以在向它发送右值时调用。有时您仍然希望编译器选择优化版本,因为您不关心变量发生了什么。功能std::move
这样做。只需将左值转换为右值即可。然后,移动构造函数执行实际移动。
在您的代码中,您这样做:
// no copy, even if AsyncLaunch is taking by
// value, since we 'move' into the value
!AsyncLaunch(std::move(aExtraOpts))
您将aExtraOpts
转换为rvalue,将数据移动到value参数中。如果函数将通过引用(或右值引用)获取其参数,那么根本就没有移动,只需引用。