mardi 2 juillet 2019

How to properly return a unique_ptr from a vector?

Let the code explain by itself:

class SomeClass {
private:
  std::vector<std::unique_ptr<MyType>> cache;
public:
  std::unique_ptr<MyType> getAt1(int i);
  MyType* getAt2(int i);
}

std::unique_ptr<MyType> SomeClass::getAt1(int i) {
  return std::move(cache[i]);
}
MyType* SomeClass::getAt2(int i) {
  return cache[i].get();
}

I'm wondering if getAt1 will make my vector inconsistent, or both ways are ok. Due to architecture flaws, I really should return as getAt1 does.

What's your opinion?

Thanks.

Aucun commentaire:

Enregistrer un commentaire