I am learning about inheritance in C++. And i came across the following statement:
In other words, the this pointer cannot be aliased in a constructor:
extern struct D d;
struct D
{
D(int a) : a(a), b(d.a) {} // b(a) or b(this->a) would be correct
int a, b;
};
D d = D(1); // because b(d.a) did not obtain a through this, d.b is now unspecified
The above example is from cppreference.
My first question is that it is written that "this
cannot be aliased in a ctor" but then in the example above, they've written in the comment "b(this->a)
would be correct". This seems to be a contradiction to me because when they said that this
cannot be aliased in a ctor i understood that "this
cannot be used in a ctor". But then why are they saying that writing b(this->a)
would be correct if this
cannot be used/aliased in a ctor. Isn't the initializer list considered "in a ctor"?
Now lets look at a custom example:
struct Name
{
private:
int x = 0;
Name(int n )
{
this->x = 4; //is the use of "this" well-defined here?
}
};
My second question is that is the use of the expression this->x
inside the converting constructor shown above well-defined? I mean since according the quote at the beginning of my question this
can't be aliased in a ctor, so this shouldn't be valid.
Aucun commentaire:
Enregistrer un commentaire