Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to a mark a function as invalidating its argument

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?

like image 304
tohava Avatar asked Mar 17 '23 18:03

tohava


1 Answers

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.

like image 72
David Avatar answered Apr 02 '23 15:04

David