The excerpt posted is not safe:
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 ending the operation, and ponteiro
invalid address reference. It’s illegal to take the address of a rvalue
.
Returning the pointer through a method is safe:
Despite the passage posted, returning the pointer through a method is safe, and the excerpt 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 you), any code scope that has access to ClasseA::getThis()
also has access to the operator &
, that has return address function:
void classequalquer::metodo() {
ClasseA A;
ClasseA * ponteiro = &A;
}
Something similar, returning a reference to you, is quite common:
Something very similar to returning a pointer to you is quite used, as in the overload
of assignment operators, where a reference to the object itself is returned (created through the de-referencing of the this
), for example:
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
}
Rodrigo, for you to have a more accurate answer, provide an example of code than
ClasseA().getThis()
returns, because as already explained well in the answer you had, the "security" of this will depend on how the allocated pointer is being manipulated beyond this code snippet.– Luiz Vieira