1

I have the following line of code

SystemFactory::system_ptr system = _Factory->createSystem(systemType);
_Systems.push_back(std::move(system));

The problem that I have is I can't just return the system as it will NULL it after moving it. The solution that I came with is the following and I don't know if it's the best one.

return (_Systems.end() - 1)->get();

If there is a better way of doing this?

Adore
  • 71
  • 7

2 Answers2

8

You can either use back():

return _Systems.back().get();

... or save it beforehand:

SystemFactory::system_ptr system = _Factory->createSystem(systemType);
auto *p = system.get();
_Systems.push_back(std::move(system));
return p;
Quentin
  • 62,093
  • 7
  • 131
  • 191
4

In C++17, std::vector::emplace_back will return a reference to the emplaced object. Therefore you'll be able to write:

SystemFactory::system_ptr system = _Factory->createSystem(systemType);
return _Systems.emplace_back(std::move(system));

Or even shorter:

return _Systems.emplace_back(_Factory->createSystem(systemType)); 
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416