Larz
Larz

Reputation: 51

Passing a vector by const reference with a custom type in C++

Say you have the custom type,

class Foo {}

Is the correct way to pass a vector of type Foo by const reference to a method like this,

void f(const std::vector<const Foo&>& bar);

or should I do,

void f(const std::vector<Foo>& bar);

I'm more curious on which one I should prefer to use.

Upvotes: 0

Views: 5580

Answers (1)

Bathsheba
Bathsheba

Reputation: 234785

You should pass const std::vector<Foo>& as the type. This prevents a value copy of the vector from being taken when the function is called.

Note that a std::vector<Foo&> is not allowed by the current standards: a std::vector cannot contain reference types.

Upvotes: 4

Related Questions