使用 *this 是个好主意吗?

发布于 2024-07-25 20:29:12 字数 391 浏览 5 评论 0原文

我不确定这是否

return *this

是我们返回调用成员函数的类实例的唯一方法? 我之所以问这个问题,是因为我们的老师告诉我们在必要时避免使用指针,我想知道在这种情况下唯一必要的方法是否是返回 this 指针。

我正在使用一个包含私有数据成员分子和分母的分数类。 我所说的成员函数用于添加两个分数,例如:

Fraction C = A.plus(B);

plus 成员函数定义如下:

Fraction& plus( const Fraction frac )

讲师希望我们执行 C = A += B ,所以我想这就是原因。

I'm not sure if

return *this

is the only way we could return an instance of a class who called a member function? The reason why I asked is because our instructor told us to avoid using pointers if necessary and I'm wondering if this is a case where the only necessary way to do it is by returning the this pointer.

I'm working with a fraction class that holds private data members numerator and denominator. The member function I'm talking about is used to add two fractions for example:

Fraction C = A.plus(B);

plus member function is defined as this:

Fraction& plus( const Fraction frac )

The instructor wants us to do C = A += B , so I guess that's why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

心在旅行 2024-08-01 20:29:12

找个新教练。 看起来 plus() 的声明是完全错误的。

  • 它可能应该返回一个值而不是引用
  • 如果它必须返回一个引用,它应该返回一个常量引用
  • 它绝对应该将常量引用作为参数

这是为了成员 plus() 函数的可能合理实现。 当然,应该是朋友。

Get a new instructor. It looks as if the declaration of plus() is completely wrong.

  • it probably should return a value rather than a reference
  • if it must return a reference, it should return a const reference
  • it should definitely take a const reference as a parameter

That is for likely sensible implementations of a member plus() function. Of course, it should probably be a friend.

め七分饶幸 2024-08-01 20:29:12

我认为在这种情况下使用它是安全的,

return *this

因为 this 引用当前对象,因此保证它存在,因此它不会为空。

plus 返回对自身的引用的原因是为了可以链接它:

Fraction C = A.plus(B).plus(D) // perhaps?

请注意,在上述情况下,C 将通过复制加法结果来创建。
这还假设操作 plus 旨在修改对象(在本例中为 A)并返回对此修改对象的引用。

难道 plus 不会接受引用而不是复制参数吗?

Fraction& plus( const Fraction& frac )

这类似于您实现 operator= 的方式(示例):

  A& operator=(const A& right) {
    if(this == &right) return *this;    // Handle self-assignment
    b = right.b;
    return *this;
  }

也许您不想修改对象并返回新对象:

// assuming there's a constructor Fraction(int numerator, int denominator):
Fraction* plus(Fraction const& rhs)
{
    return new Fraction(numerator * rhs.denominator
                        + rhs.numerator * denominator,
                        denominator * rhs.denominator);
}

但这当然必须返回指向新实例的指针,该实例不是您的任务中可能需要的参考(?)。

或者甚至更好:

Fraction plus(Fraction const& rhs)
{
    return Fraction(numerator * rhs.denominator
                    + rhs.numerator * denominator,
                    denominator * rhs.denominator);
}

这将在调用函数的空间中创建 Fraction,因此在返回时没有复制结构的开销。

I think in this case it is safe to use

return *this

because this refers to the current object so it is guaranteed to exist, so it won't be null.

The reason plus returns reference to itself is so that it can be chained:

Fraction C = A.plus(B).plus(D) // perhaps?

Note that in the above case C will be created by copying the result of addition.
This also assumes that operation plus is meant to modify object (in this case A) and return the reference to this modified object.

Wouldn't plus accept reference instead of making copy of the parameter?

Fraction& plus( const Fraction& frac )

This is similar to how you would implement operator= (an example):

  A& operator=(const A& right) {
    if(this == &right) return *this;    // Handle self-assignment
    b = right.b;
    return *this;
  }

Maybe you would want to not modify object and return new object:

// assuming there's a constructor Fraction(int numerator, int denominator):
Fraction* plus(Fraction const& rhs)
{
    return new Fraction(numerator * rhs.denominator
                        + rhs.numerator * denominator,
                        denominator * rhs.denominator);
}

But this of course has to return pointer to new instance which is not a reference as maybe required in your task (?).

Or even better:

Fraction plus(Fraction const& rhs)
{
    return Fraction(numerator * rhs.denominator
                    + rhs.numerator * denominator,
                    denominator * rhs.denominator);
}

This will create Fraction in the space of calling function so there's no overhead of copying structure on return.

薆情海 2024-08-01 20:29:12

是的,这是唯一的方法。 在方法中访问当前对象的唯一方法是通过 this,它是一个指针。

这很好,并且是一种可接受的做法。

Yes, this is the only way. The only way to access the current object in a method is via this, and it is a pointer.

It is fine, and is an accepted practice.

清风无影 2024-08-01 20:29:12

返回 *this 没有任何问题。 例如,这就是修改运算符的重载应该如何工作的。 看起来 plus 方法实际上只是为您的类提供运算符+= 的一种方法,而无需实际重载运算符(我假设您还没有实现运算符重载),因此返回 *this这种情况是常见的行为。

There's nothing wrong with returning *this. For example, that's how overloads of modifying operators are supposed to work. It seems like the plus method is really just a way of providing an operator+= for your class without actually overloading the operator (I assume you haven't gotten to operator overloading yet), so returning *this in this case is the usual behavior.

一生独一 2024-08-01 20:29:12

在您的 plus() 方法中,您可能应该创建一个新的 Fraction 对象并返回该对象,而不是修改当前对象然后返回 *this 。 您可能不想更改 A.plus(B) 中的 A。 要返回新的 Fractionplus() 的签名最好是:(

Fraction plus(const Fraction &frac);

如果您当前没有在 this 中修改 this code>plus()方法,为什么要返回*this?)

In your plus() method you should probably create a new Fraction object and return that, instead of modifying the current one and then returning *this. You probably don't want to change A in A.plus(B). To return a new Fraction, the signature of plus() would best be:

Fraction plus(const Fraction &frac);

(In case you're not currently modifying this in the plus() method, why do you want to return *this?)

打小就很酷 2024-08-01 20:29:12

我认为语义应该是成员函数“plus”返回一个“新”对象,该对象表示调用者和被调用者的总和。
注意 :: new 并不意味着 C++ 中的“new”关键字:)
因此,对于您的示例,

// the constructor accepts (numerator, denominator).
// in your case, the caller object would be A, and the called object would be B(other).
return Fraction(numerator * other.denominator + other.numerator * denominator, denominator * other.denominator);

我认为返回对此引用的唯一正确位置是当您重载具有副作用的运算符时。

为了更清楚地说明,这应该是您的“加号”签名,

Fraction plus( const Fraction& frac );

呼叫者和被叫者都不应受到“加号”的影响。

I believe that the semantics should be that the member function 'plus' returns a 'new' object which represents the sum of the caller and the called.
note :: new does not mean 'new' keyword in C++ :)
so for your example,

// the constructor accepts (numerator, denominator).
// in your case, the caller object would be A, and the called object would be B(other).
return Fraction(numerator * other.denominator + other.numerator * denominator, denominator * other.denominator);

The only place I see it correct to return a reference to this is when you overload operators that have side effects.

To clarify more, this should be your 'plus' signature,

Fraction plus( const Fraction& frac );

neither the caller nor the called should be effected by the 'plus'.

呆° 2024-08-01 20:29:12

我们的老师告诉我们必要时避免使用指针

您实际上返回的是取消引用指针的值,而不是指针。 所以你应该很好。

就我个人而言,我从不显式调用方法或通过 this 引用成员。 也就是说,我不执行以下操作:

class A {
    public:
    int x;
    int get_x()
    {
        return this->x;
    }

    int get_x_plus_5()
    {
        return this->get_x() + 5;
    }
}

但是,我完全可以返回 *this

你的导师可能试图让你避免(1)从函数返回指向堆栈上对象的指针(这意味着它们在函数退出后将不存在)和(2)当你不这样做时在空闲存储上分配对象不必。 this 不会遇到这些问题。

our instructor told us to avoid using pointers if necessary

You're actually returning the value of dereferencing a pointer, not the pointer. So you should be good.

Personally, I never explicitly call methods or refer to members via this. That is, I DO NOT do the following:

class A {
    public:
    int x;
    int get_x()
    {
        return this->x;
    }

    int get_x_plus_5()
    {
        return this->get_x() + 5;
    }
}

However, I am perfectly fine with returning *this.

Your instructor probably is trying to get you to avoid (1) returning pointers to objects on the stack from functions (which means that they won't exist after the function exits) and (2) allocating objects on the free store when you don't have to. this doesn't suffer from either of those issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文