tower120
tower120

Reputation: 5255

C++ getter temporary vs const reference

I have some class that stores vector. And I have getter for it

class Data{
  private:
    std::vector<Point*> points;

  public:
    inline std::vector<Point*> getPoints(){
      return points;
     }

}

When I call getPoints() will it return temporary object? Or it will just copy it?
Or I should return const reference, instead?

UPDATE


And what if I have another class that hold my Data, which also have a getter:

class Controller{
private:
  Data *data;

public:
  inline std::vector<Point*> getPoints(){
     return data->getPoints();
  }
}

Should both of them be const reference, if I want them not to be copied?

Upvotes: 1

Views: 803

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

Your method makes a copy of points. Modifications to the vector itself will not be propagated to the points inside your class. You could return a const reference instead to avoid copying. The caller would be able to copy if he wants, but he would be in control.

Note that the copy that is made when returning a vector is shallow. This means that the individual points are exposed: if the caller makes modifications to points (as opposed to making modifications to the vector) these modifications will propagate to the points pointed to by the vector inside your class.

Protecting the content of Points is a lot harder - it would require you to do manual copying. It would also require your caller to make manual freeing. In general, though, you would be better off using smart pointers (std::unique_ptr or std::shared_ptr) for easier resource management.

Upvotes: 2

erenon
erenon

Reputation: 19118

It will copy your original vector.

Return a const reference if you don't want to have it that way.

Upvotes: 0

Related Questions