I have a function f
that accepts a vector of pointers. Once the function f
finishes, these pointers are no longer valid. Note, there is no real need to change the vector itself, I just want to encourage callers not to use the pointers after the call to f
. There are three possible signatures for f
:
The move signature
void f(vector<void*> &&v); // because the pointers in v are no longer valid.
// This signature also allows me to have f call clear() on v.
The const signature
void f(const vector<void*> &v); // because the pointers in v are no longer valid,
// but we don't have to change the vector v.
The pointer signature
void f(vector<void*> *v); // The functino modifies v in a predictable way
// (it clears it). A pointer is used instead of a reference so that
// calls to the function will have a '&' which clearly shows to the reader
// that this function modifies its argument. '*' is different from '&&' since '&&'
// may imply "do not use v, but it is unknown how it will be modified" while
// '*' implies a clear semantic for how v is changed.
Which signature is more idiomatic to use in C++11?
How about
void f(vector<void*> v);
And to use it:
vector<void*> myVec = /*...*/;
f(std::move(myVec));
If f
logically needs ownership of a vector, this is the idiomatic way. It allows the caller to decide whether to move or copy a vector to f
.
If the caller actually wants f
to modify his vector (so the vector is actually an in/out argument) then this doesn't suit your needs. However in/out arguments suck. Functions should take input as arguments and return output as a return value. That's what god intended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With