我有一个函数 f
接受一个指针 vector 。一旦函数 f
完成,这些指针就不再有效。请注意,实际上没有必要更改 vector 本身,我只是想鼓励调用者不要在调用 f
之后使用指针。 f
有三种可能的签名:
move 签名
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.
常量签名
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.
指针签名
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.
在 C++11 中使用哪个签名更惯用?
最佳答案
怎么样
void f(vector<void*> v);
并使用它:
vector<void*> myVec = /*...*/;
f(std::move(myVec));
如果 f
逻辑上需要 vector 的所有权,这是惯用的方式。它允许调用者决定是将 vector move 还是复制到 f
。
如果调用者实际上希望 f
修改他的 vector (因此 vector 实际上是一个输入/输出参数)那么这不符合您的需要。然而,输入/输出参数很糟糕。函数应该将输入作为参数并返回输出作为返回值。这就是上帝的意图。
关于c++ - 如何将函数标记为使其参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29064484/