To satisfy your curiosity, yes you can delete
it safely, but only if you return it by reference (pointer or C++ reference (&
)). By reference so as to retain the original address of your new
ed object. You need that address for you to correctly and safely delete
your object.
int& create_ref(){
int *x = new int;
*x =5;
return *x;
}
int* create_ptr(){
int *x = new int;
*x =5;
return x;
}
int create_sane_version() {
return 5;
}
int main(){
int& x = create_ref();
delete &x; // OK. Get address of x; same as deleting through a pointer pointing to its address
// x here refers to the newed object inside create_ref() (*x)
// Still begs the question of why you're painstakingly doing this
int* y = create_ptr();
delete y; // OK, but not optimal (the above isn't either)
// * not optimal == a bad way to do this
int leak = create_ref();
delete &leak; // DEFINITELY NOT OK. leak isn't the same as the newed object
// i.e. &leak != &create_ref();
// You're actually *copying* the object referred to by the returned
// reference. The returned reference gets lost.
int best_way_to_do_this = create_sane_version();
}