前缀/后缀增量运算符 [英] Prefix/Postfix increment operators

查看:211
本文介绍了前缀/后缀增量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我能正确理解通过值传递与按引用传递。特别是,我正在查看一个对象的增量 ++ 运算符的前缀/后缀版本。

I'm wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++ operator for an object.

让我们假设我们有以下类 X

Let's suppose we have the following class X:

class X{
private:
    int i;
public:
 X(){i=0;}
 X& operator ++ (){ ++i; return *this; } //prefix increment

 X operator ++ (int unused){ //postfix increment
  X ret(*this);
  i++;
  return ret;
 }

 operator int(){ return i; } //int cast
};

首先,我是否正确实现了前缀/后缀增量运算符?

First of all, have I implemented the prefix/postfix increment operators properly?

其次,与前缀运算符相比,后缀运算符如何具有内存高效性?具体来说,当使用每个版本的操作符时,会创建多少个 X 对象副本?

Second, how memory-efficient is the postfix operator, compared to the prefix operator? Specifically how many X object copies are created when each version of the operator is used?

编辑:例如,使用以下代码...

For example, with the following code...

X a;
X b=a++;

... a和b现在是别名吗?

...are a and b now aliases?

推荐答案

这是一个正确的实现。通常,后缀操作符会更糟的性能,因为你必须创建另一个副本之前做增量(这就是为什么我总是使用前缀的习惯,除非我需要别的东西)。

This is a correct implementation. It is typical that a postfix operator will be worse on performance because you have to create another copy before doing the increment (and this is why I've gotten in the habit of always using prefix unless I need something else).

通过引用返回,您将返回当前对象的l值引用。编译器通常通过返回当前对象的地址来实现这一点。这意味着返回对象就像返回一个数字一样简单。

With return-by-reference, you're returning an l-value reference to the current object. The compiler would typically implement this by returning the address of the current object. This means that returning the object is as simple as returning a number.

但是,通过按值返回,必须进行复制。这意味着在返回期间有更多的信息要复制(而不仅仅是一个地址),以及要调用的复制构造函数。

However, with return-by-value, a copy must be done. This means there's more information to copy over during the return (instead of just an address) as well as a copy constructor to call. This is where your performance hit comes in.

您的实现效率与典型实现的效果一致。

The efficiency of your implementation looks on-par with typical implementations.

编辑:
关于你的附录,不,他们不是别名。您已创建两个单独的对象。当你按值返回时(当你在postfix增量操作符中创建一个新对象时),这个新对象被放置在一个不同的内存位置。

With regards to your addendum, no, they are not aliases. You have created two separate objects. When you return by value (and when you created a new object from within the postfix increment operator) this new object is placed in a distinct memory location.

以下代码,a和b 是别名:

However, in the following code, a and b are aliases:

 int a = 0;
 int& b = ++a;

b是引用a。的地址。

b is an address which references a.

这篇关于前缀/后缀增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆