I have following problem:
Let's assume I have a Vector with 100 Objects, therefore it would be bad to create a copy.
class MyClass
{
private:
vector<MyObject> mVector;
};
//return by reference
vector<object>& MyClass::GetVector1()
{
return mVector;
}
vector<object>* MyClass::GetVector2()
{
return &mVector;
};
return by reference is fast and generates no copy. The vector should be still available in MyClass, therefore i don't want to move it. But what would be the best way to use this GetVector() method?:
class MyOtherClass
{
private:
vector<MyObject>* myVector;
vector<MyObject>& myVector2;
vector<MyObject> myVector3;
MyClass m;
};
myVector2 = m.GetVector1(); //only works in an initializer list!
But what if I can't initialize the vector when the object is created? Let's assume I have a OnInit() method which will be called when it's needed:
void MyOtherClass::OnInit()
{
myVector = m.GetVector2(); //no copy using return by reference
myVector = &m.GetVector1(); //no copy returning a pointer
myVector3 = m.GetVector1(); //copy
}
Lots of people told me using pointers like myVector is very bad, but why????? Should I use smart_pointers instead? (Please give me a example, how to use them with the given code above)
Or are there better ways to get fast performance?.
Edit:
for the answer check my selected answer for this below.
additionally I want to add move semantics.
But this heavily depends on the purpose of the code, sometimes you really want to copy, you won't be able to avoid it. If you know the object last longer than the code tracking it, pointers are fine as long as you want changes to apply as well, otherwise use const ref.
If you don't need the object you return anymore and it might get destroyed, you would use return by value, which is ok since the compiler might optimize it by moving, but you can explicitly make use of movesemantics and move the vector out of the class, since the vector elements are dynamically allocated and the container is moveable. check this link: Is returning by rvalue reference more efficient?