I’ve got a function that takes a pointer to an object of a custom class (actually pointers to a base class such that polymorphism works). Within the calling routine this object however is exclusively needed for the purpose of this call, i.e. is temporary. For example like this:
class A { /** stuff */ };
class B : public A { /** stuff */ };
void doSomething( const A* const _p ) { /** stuff */ }
void callingRoutine()
{
A* tempPointer = new B;
doSomething( tempPointer );
delete tempPointer;
}
Now, since I really only need the object of type B within the call to doSomething, is there a way to do it in one line? Doing
doSomething( new B );
creates memory leaks (valgrind says so). Or would
doSomething( &B );
be the recommended way? The latter compiles but gives warnings about passing pointers to temporary objects. This is what I want to do, but would it be safe this way?
The cleanest way is to do
But what you really should write depends of what the
doSomethingfunction does. If it’s fine to destructbat the end ofcallingRoutine, then it’s the faster and cleaner way to do this, because allocating on the stack is faster thannewand does not require you to deletebafterwards.