【发布时间】:2015-03-15 18:26:06
【问题描述】:
我有一个函数f,它接受一个指针向量。一旦函数f 完成,这些指针就不再有效。请注意,没有真正需要更改向量本身,我只是想鼓励调用者在调用f 之后不要使用指针。 f 有三种可能的签名:
移动签名
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.
const 签名
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 中使用哪个签名更惯用?
【问题讨论】:
-
const vector&根本不允许您修改向量,并且只有在“无参数”是一个合理的参数时传递指针才有意义。第一个变体不接受左值,这很奇怪。只需按值传递,让调用者决定他想要移动还是复制。 -
这些签名实际上都没有说明/保证关于向量内的指针(更不用说指针)的任何内容,而只是关于向量本身。
-
@KonradRudolph -
&&签名在语义上意味着“这个函数可以将v修改为可破坏的所有内容,所以不要依赖 v 的内容”,这非常接近,不要你觉得呢? -
@tohava 不。就像你说的,签名说“不要依赖向量的内容”,但这无关紧要。如果调用者有不同的指针指向同一个资源怎么办?如果指针表示所有权 (
unique_ptr),您的签名将有意义。 -
@tohava 并不是说这不完美,而是会产生误导:没有人会按照您的意图理解签名,因为类型系统根本不传达此信息;您的签名传达了不同的正交信息。你有两个选择:要么正确地编码它(例如通过使用前面提到的
unique_ptrs),要么根本不尝试(错误地)在类型系统中编码它,而是依赖文档和测试。跨度>
标签: c++ c++11 types move-semantics rvalue-reference