Xavier
Xavier

Reputation: 9049

Pushing onto an STL stack is pass by reference, but does the stack make a copy of the value?

Checking the documentation online I saw that it is pass by reference. Can someone confirm that the stack actually makes a copy of the data?

Upvotes: 1

Views: 2041

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490328

The parameter to the stack adapter itself is by reference, but remember that stack is just an adapter -- its push immediately calls the push_back, passing that same parameter. This call, however, passes the parameter by value.

Therefore, the parameter you pass does get copied -- the pass by reference to std::stack means that it only gets copied once. If that was a pass by value, then it would be copied twice (ignoring, for the moment, the compiler eliding the copy, which it almost certainly would).

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473926

Yes, it does copy the element you give it. In C++11, it can also move it if you give it a temporary or std::move into it.

Note that C++11 also offers emplace, which directly constructs the value in-place, given constructor arguments.

Upvotes: 7

He Shiming
He Shiming

Reputation: 5819

It depends. The value is copied but it might not work as you thought. If you are pushing a pointer, such as char*, it'll copy just the pointer value, and not the entire string. If you are pushing a simple int, or CustomObject but not the pointer, it'll be copied.

Upvotes: 1

Related Questions