0

When I pass a std::vector into a C++ function, like so:

void myFunc(std::vector<int> myVec)
{
// do something
}

Does the vector myVec get copied or is in reality only a pointer passed? I'm asking from optimization perspective; should I always explicitly pass a pointer to the vector or is there a difference in speed? Assume that I only want to read the data in the function, not manipulate the vector itself.

A. McMount
  • 141
  • 6
  • 1
    It is a copy in your example. Also use const if you don't manipulate data. A reference is always prefered. – YesThatIsMyName Sep 20 '22 at 07:04
  • 3
    *Assume that I only want to read the data in the function* Then you pass a `const &`. Passing things by pointer is generally not what you want. – super Sep 20 '22 at 07:04
  • 1
    It is called **pass by value**. This is explained in any beginner [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Also see [Why pass by const reference instead of by value?](https://stackoverflow.com/questions/2582797/why-pass-by-const-reference-instead-of-by-value). And [Which is faster? Pass by reference vs pass by value C++](https://stackoverflow.com/questions/26552481/which-is-faster-pass-by-reference-vs-pass-by-value-c) – Jason Sep 20 '22 at 07:05
  • put meaning and correctness first. The reason to pass by value or by reference is mainly because you either need a copy or not a copy. Performance follows from writing code that expresses what it should do rather than something else, because your compiler knows how to emit efficient output – 463035818_is_not_an_ai Sep 20 '22 at 07:52

0 Answers0