The posted post is not secure:
void classequalquer::metodo() {
ClasseA * ponteiro = ClasseA().getThis();
//deferenciar o ponteiro aqui é comportamento indefinido
//o objeto não existe mais
}
ponteiro
takes the address of an object created as temporary for the assignment operation. The object is not available at the end of the sequential point that terminates the operation, and ponteiro
reference address invalidated. It is illegal to get the address of a rvalue
.
Returning the pointer through a method is safe:
Despite the posted snippet, returning the pointer through a method is safe, and the snippet should be adapted to the following form:
void classequalquer::metodo() {
ClasseA A;
ClasseA * ponteiro = A.getThis();
//usa o ponteiro nesse método sem usar delete
//o objeto ainda existe
}
But the method is unnecessary (and I personally discourage it), any code scope that has access to ClasseA::getThis()
also has access to the &
operator, which has the function of returning address:
void classequalquer::metodo() {
ClasseA A;
ClasseA * ponteiro = &A;
}
Something similar, returning a reference to you, is very common:
Something very similar to returning a pointer to itself is often used, as in the% of assignment operators, where you return a reference to the object itself (created by dereferencing overload
), for example: / p>
ClasseA& ClasseA::operator = (ClasseA const & outra) {
//..(algumas operações de atribuição)..
return *this; //semelhante a retornar ponteiro, (refere-se a este objeto)
//mas a referência é mais transparente.
//assim como o ponteiro,
// a referência será invalidada quando o objeto for destruído
}