Is it possible to pass * this in the constructor in the following example

Class A
{
  A(B& b) : mb(b) 
   {
     // I will not access anything from B here
    }

  B& mb;
};


Class B
{
B(): a(*this)
{}

A a;
}

I may encounter such a situation, it may take time, for the object contained in the container, it is necessary to use the functionality of the containers. This seems to be the best way to link to a container object in the contained object. Of course, I could do this with a pointer, so I could have a setter setB(B* b) {mb = b;}, which I could name later after I am sure that B is initialized, but I would prefer to do this with a link, which means that I need to initialize this in the constructor, hence the problem.

+3
source share
3 answers

:

§3.8 [basic.life]/6

, , , , , , , , , , lvalue , . lvalue (3.7.3.2), lvalue, , . lvalue lvalue-rvalue (4.1), undefined; , POD, undefined, :

— the lvalue is used to access a non-static data member or call a non-static member function of the object, or 
— the lvalue is implicitly converted (4.10) to a reference to a base class type, or 
— the lvalue is used as the operand of a static_cast(5.2.9) (except when the conversion is ultimately to char& or unsigned char&), or 
— the lvalue is used as the operand of a dynamic_cast(5.2.7) or as the operand oftypeid.
+1

B, - , B , .

, B , B .

+9

, A.

B , . , , B, B . :

class B
{
    A a;
    std::string str;

public:
    B() : a(*this)
    {
    }
};

, A::A, str . str A::A ( ), undefined.

+1

Source: https://habr.com/ru/post/1737836/


All Articles