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?

4
  • 4
    Names like _Factory and _Systems are IIRC reserved for the implementation in all scopes. Commented Feb 23, 2017 at 15:16
  • 3
    OT: _Systems is an implementation reserved identifier, you cannot use it. Also, starting variable names with an uppercase letter is somewhat uncommon. Commented Feb 23, 2017 at 15:16
  • 3
    Link to rules for naming identifiers. Commented Feb 23, 2017 at 15:17
  • Well, what are you trying to do? You didn't actually say. Commented Feb 23, 2017 at 15:54

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.