'this' in constructor and object creation

I read some articles when it says that you should not use the 'this' keyword in the constructor, while others should be the exact opposite ....

Now my main question is: is it safe and good to use the 'this' constructor in the constructor?

This question leads to others:

  • How is an object created?
  • When are class members created? Before calling the constructor?

Here are some examples of working with VS2012 on windows 7:

class FirstClass { int m_A; public: FirstClass( int a ) : m_A( a ) { std::cout << this->m_A << std::endl; // ^^^^ } }; 

and:

 class ThirdClass; // forward decl class SecondClass { public: SecondClass( ThirdClass* iTC ) { // ... } }; class ThirdClass { SecondClass* m_SC; public: ThirdClass(): m_SC( new SecondClass( this ) ) // ^^^^ { //... } }; 

These examples work, but is it likely to have undefined behavior?

+4
source share
2 answers

Since the memory for the object and its members is allocated before calling the constructor, the value of the this pointer itself is not a problem: these are members that you could separate from it, which can be a problem.

Your first piece of code is valid because this->m_A is identical to m_A , which is a valid expression.

The second piece of code may or may not be in order, depending on what the SecondClass constructor SecondClass :

  • If the SecondClass constructor simply stores a pointer to FirstClass for future use, that's OK
  • If the SecondClass constructor calls the deviation methods from the pointer to FirstClass passed to it, this is not so because the instance pointed to by the this pointer was not initialized.
+9
source

Firstly, yes, it is completely safe to use the 'this' keyword. In the case of all the participants that are on the stack, the 'this' keyword will work fine and those that are a pointer type, you must first assign them a memory, and then use them with the keyword 'this'. if you do not assign memory or try to use it, this will create a problem. Secondly, you asked how an object is created and when class members are created, they are created when you make a class object, either mainly or in any function.

+1
source

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


All Articles