foo * bar(foo * useme=0);
where one can optionally pass memory to be used, but if nothing is passed, it will be allocated by the function (placement new can be helpful here!).
foo * bar(foo * useme=0);
where one can optionally pass memory to be used, but if nothing is passed, it will be allocated by the function (placement new can be helpful here!).
In C++, a better thing would be to take advantage of overloading directly:
foo *bar(foo *); // doesn't allocate; non-null required
foo *bar(); // allocates
Then there is no run-time check of the pointer value for null. bar() is just a wrapper like: foo *bar() { return bar(new Foo); }
Moreover, the value provided by bar() is pretty low; it's like a syntactic sugar that rewrites bar() to bar(new Foo). I'd consider not adding that to the API.You are over-nitpicking. It's obvious that the GP meant that you can pass NULL by default if needed.
But the way the overloads are collapsed into a single function, there has to be a run-time check for that null.
Using a null to indicate "argument is not there" is a C API trick. That parameter won't be optional in C.
If you're especially unlucky, that garbage data will happen to be NULL at first, but then become non-NULL when you recompile with debugging turned off, resulting in truly fascinating ways to spend your Friday and Saturday nights the month before shipping.
(I know you know this, Kaz. I'm mentioning this for the benefit of those who haven't yet spent their Friday and Saturday nights this way.)
void foo(void* p=0); // has exactly the same ABI as
void bar(void* p);
bar(); // error: missing parameter
foo(); // shorthand for foo(0);
// void(*)(void*) is a different type than void(*)(void*=0)
// but they can be implicitly converted the same as
// eg void* and char* // Definition
foo * bar(foo * useme);
And then use as // Allocate foo for me pls.
foo * result = bar(NULL)
or // I'll allocate the buffer myself ktkxbye.
foo * result = bar(malloc(…))The pattern is more useful when there are more arguments to foo and you don't want to have bar(int a, int b, double c, foo * useme) and bar(int a, int b, double c) in the API.
double * doMathOperation(unsigned N, const double * in, double aux1, double aux2, double * out = 0);
(obviously, in C, you would leave the = 0 out and document it instead).