c++ - 如何将函数标记为使其参数无效

标签 c++ c++11 types move-semantics rvalue-reference

我有一个函数 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/

相关文章:

scala - 没有案例类的模式匹配

generics - Scala 递归泛型 : Parent[Child] and Child[Parent]

c++ - epoll数据结构中同时使用void *ptr和int fd

c++ - 在 C++ 中设置二维数组的默认值

c++ - CUDA 会悄悄地向下转换 double 来 float 吗?

c++ - 在单元测试中验证 static_assert

c++ - 当我在并行合并排序中增加 vector 的大小时出现段错误

c++ - boost 、几何

c++ - Win-builds 与 MinGW-builds 之间的区别

haskell - 我可以创建一个类似于 Int 的 'Looks' 仿函数数据类型吗?