重载增量的返回值
Stroustrup 在他的《C++ 编程语言》中给出了以下 inc/dec 重载的示例:
class Ptr_to_T {
T* p;
T* array ;
int size;
public:
Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p
Ptr_to_T(T* p); // bind to single object, initial value p
Ptr_to_T& operator++(); // prefix
Ptr_to_T operator++(int); // postfix
Ptr_to_T& operator--(); // prefix
Ptr_to_T operator--(int); // postfix
T&operator*() ; // prefix
}
为什么前缀运算符按引用返回,而后缀运算符按值返回?
谢谢。
In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading:
class Ptr_to_T {
T* p;
T* array ;
int size;
public:
Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p
Ptr_to_T(T* p); // bind to single object, initial value p
Ptr_to_T& operator++(); // prefix
Ptr_to_T operator++(int); // postfix
Ptr_to_T& operator--(); // prefix
Ptr_to_T operator--(int); // postfix
T&operator*() ; // prefix
}
Why prefix operators return by reference while postfix operators return by value?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设我使用重载预增量来递增私有成员。 返回对私有成员的引用是否不会将 ++private_var 表达式转换为左值,从而可以直接修改私有成员?
Suppose I use overloaded preincrement to increment a private member. Doesn't returning a reference to a private member turns the ++private_var expression to an lvalue thus making it possible to modify the private member directly?
后缀运算符返回值递增之前的副本,因此它几乎必须返回临时值。 前缀运算符确实返回对象的当前值,因此它可以返回对其当前值的引用。
The postfix operator returns a copy of the value before it was incremented, so it pretty much has to return a temporary. The prefix operator does return the current value of the object, so it can return a reference to, well, its current value.
为了更好地理解,您必须想象(或看看)这些运算符是如何实现的。 通常,前缀operator++或多或少会写成这样:
由于
this
已被“就地”修改,我们可以返回对实例的引用以避免无用的副本。现在,这是后缀运算符++的代码:
由于后缀运算符返回一个临时值,因此它必须按值返回它(否则,您将得到一个悬空引用)。
C++ Faq Lite 也有一段就此主题而言。
To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this:
Since
this
has been modified "in-place", we can return a reference to the instance in order to avoid a useless copy.Now, here's the code for the postfix operator++:
As the postfix operator returns a temporary, it has to return it by value (otherwise, you'll get a dangling reference).
The C++ Faq Lite also has a paragraph on the subject.