如何在 C++ 中传递“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1823816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:16:12  来源:igfitidea点击:

how to pass "this" in c++

c++

提问by cplusplusNewbie

I'm confused with the thiskeyword in C++, I'm not sure that if I'm doing the right thing by passing this. Here is the piece of code that I'm struggling with:

我对thisC++ 中的关键字感到困惑,我不确定通过传递this. 这是我正在努力解决的一段代码:

ClassA::ClassA( ClassB &b) {

    b.doSth(this);
    // trying to call b's routine by passing a pointer to itself, should I use "this"?
}

ClassB::doSth(ClassA * a) {
       //do sth
}

回答by cchampion

You're using it correctly. The this pointer points to the current object instance.

您正在正确使用它。this 指针指向当前对象实例。

class helper 
{
public:
     void help(worker *pWorker) {
          //TODO do something with pWorker . . .
     }

     void help2(worker& rWorker) {
          //TODO do something with rWorker . . .
     }
};

class worker 
{
public:
     void dowork() {
          //this one takes a worker pointer so we can use the this pointer.
          helper.help(this);

          //to pass by reference, you need to dereference the this pointer.
          helper.help2(*this);
     }
     helper helper;
};

Also, say you declare worker *pW = new worker(). If you call one of the methods (dowork) on the pWobject, you will notice that the thispointer and pW have the exact same value (they are both the same address).

另外,假设您声明worker *pW = new worker(). 如果您在pW对象上调用其中一种方法 (dowork) ,您会注意到this指针和 pW 具有完全相同的值(它们都是相同的地址)。

(haven't tested that to make sure it builds, but I think it should).

(尚未测试以确保它可以构建,但我认为它应该)。

回答by LeopardSkinPillBoxHat

In C++, thisis a keyword which is defined as "the pointer to the current object instance". So your code above is correct.

在 C++ 中,this是一个关键字,定义为“指向当前对象实例的指针”。所以你上面的代码是正确的。

Depending on the inheritance/composition relationship between ClassAand ClassB, there are probably better ways to achieve what you are doing than by using the thispointer.

根据ClassA和之间的继承/组合关系ClassB,可能有比使用this指针更好的方法来实现您正在做的事情。

回答by Richard Corden

It's perfectly OK to pass 'this' or '*this' as you are doing.

像您一样传递 'this' 或 '*this' 是完全可以的。

Lifetime Dangers:

终身危险:

One point about the example you've supplied is that you're calling doSthfrom the constructor of ClassA. The object that's passed to doSthis possibly a partially constructed object:

关于您提供的示例的一点是,您是doSthClassA. 传递给的对象doSth可能是部分构造的对象:

class ClassC {
public:
  ClassC ()
  : m_c ()
  {}
  int m_c;
};

class ClassA : public ClassC {
public:
  ClassA (ClassB & b)
  : ClassC ()
  , m_b ( b.doSth (this) )  // ClassC constructed
                            // ClassA members partially init.
  {
    b.doSth (this);         // ClassA members initialized
  }

  // ...
  int m_a;
};

class ClassD : public ClassA {
public:
  ClassD(ClassB & b)
  : ClassA (b)              // Partially init
  , m_d ()
  {
                            // ClassC and ClassA constructed
                            // ClassD members initialized
  }
  int m_d;
};

There may be problems if doSthuses members that have not yet been initialized:

如果doSth使用尚未初始化的成员可能会出现问题:

void ClassB::doSth (ClassA * a) {
  int i = a->m_c;     // OK m_c is initialized

  int j = a->m_a;     // Not OK, m_a not initialized when called
                      // from member initialization list.

  int k = static_cast<ClassD*> (a).m_d;  // Not OK
}

Using the dynamic type of the object:

使用对象的动态类型:

Finally, any use of the dynamic type of the object (eg. virtual calls, dynamic_cast, typeid) will have different results on a partially constructed object than on a complete object (and in some case you can have undefined behaviour).

最后,任何使用对象的动态类型(例如,虚拟调用、dynamic_cast、typeid)在部分构造的对象上将与在完整对象上产生不同的结果(在某些情况下,您可能有未定义的行为)。

void ClassB::doSth (ClassA * a) {
  if (ClassD * d = dynamic_cast<ClassD *> (a))
  {
    // Never true when called from ClassA::ClassA
  }
}

回答by red.clover

In this case using thiswill pass a pointer to the caller class, which is A, to b.DoSth. It seems that you are doing it right. thiskeyword always points to the class instance that you are using it from.

在这种情况下, usingthis会将一个指向调用者类的指针,即 A,传递给 b.DoSth。看来你做得对。this关键字始终指向您从中使用它的类实例。

回答by empc

thisis a pointer to the object instance, so what you are doing is correct.

this是一个指向对象实例的指针,所以你在做什么是正确的。

Read thisfor more information.

阅读本文了解更多信息。

回答by aJ.

thisis a const pointer to its own object. thispointer is nonmodifiable.

this是一个指向它自己对象的常量指针。this指针是不可修改的。

  ClassA::ClassA( ClassB &b) {

        b.doSth(this);
        // here 'this' refers to this object ie the instance of ClassA. 
        // When you pass 'this' to doSth function --> is equivalent to passing 
        // the instance of current object of ClassA.
        //   
    }