Is it in anyway possible (without using boost) to have a function in c++ as follows :
void foo(int x, classX &obj = *(new classX()))
The classX
is used multiple times in my codebase and there are many such functions which have a similar signature (i.e. use this class object as a default argument). Is it possible to achieve this without an overloaded call?
The code that you provided certainly compiles and "works", but I strongly advise against such a thing.
The function returns void
so that means the either referenced or allocated object (or its presumed owner) does not leave the function. It must thus, if allocated, be destroyed (otherwise, that's someone else's problem, outside that function).
However, that isn't even possible, there is nobody who owns the object, or has a pointer to it! So not only do you have a possible memory leak there, you have a guaranteed memory leak (in case no object is passed), unless you add yet another ugly hack that derives a pointer from the reference only to destroy the object. That's very unpleasant.
Plus, even if you get this done (in a no-leak way), you have useless object allocation and destruction for every function call. Although one shouldn't optimize prematurely, one also shouldn't pessimize prematurely by adding regular allocations and deallocations that are not just unnecessary but actually decrease code quality.
Something that's better would be:
//namespace whatever {
classX dummy;
//}
#include <memory>
void foo(int x, classX &obj = dummy)
{
if(std::addressof(obj) != std::addressof(dummy))
{ /* do something using object */ }
else
{ /* no object supplied */ }
}
Yep, that's a global used for a good cause. You can make the global a singleton if that makes you feel better, or a static class member, all the same. Either way, you have exactly one object, no allocations, no leaks, and you can still pass an object to the function if you wish. And, you can distinguish these two cases.