C++ unique_ptr向量

And*_*tor 1 c++ unique-ptr

我有以下代码行

SystemFactory::system_ptr system = _Factory->createSystem(systemType);
_Systems.push_back(std::move(system));
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我不能只返回系统,因为它在移动后会为NULL.我带来的解决方案如下,我不知道它是否是最好的解决方案.

return (_Systems.end() - 1)->get();
Run Code Online (Sandbox Code Playgroud)

如果有更好的方法吗?

Que*_*tin 8

你可以使用back():

return _Systems.back().get();
Run Code Online (Sandbox Code Playgroud)

...或事先保存:

SystemFactory::system_ptr system = _Factory->createSystem(systemType);
auto *p = system.get();
_Systems.push_back(std::move(system));
return p;
Run Code Online (Sandbox Code Playgroud)