Captain Jack sparrow
Captain Jack sparrow

Reputation: 1019

is delete called on a c++ default pointer parameter

I have a function that instantiates a pointer by default if it is not supplied with the second parameter.

void doSomething(int a, Obj* obj = new Obj()) {
...
}

Do I need to call an explicit delete inside the function if I want to release obj or it is done automatically if I had instantiated the pointer from the default param values?

I want to avoid doing an explicit delete myself since if the second argument is passed then I don't want to delete the pointer passed by the caller.

Upvotes: 3

Views: 81

Answers (1)

AndyG
AndyG

Reputation: 41110

It sounds like your memory ownership semantics need a rework. In some cases you own the memory and others you don't. If you insist on default creating an instance of Obj, then also accept a boolean that indicates whether you own the memory or not. In the end, though, I actually suggest you use overloading instead to accomplish this, where one function takes one argument and the other two. The one that only accepts one will create an instance of Obj and then call your base doSomething function.

Something like:

void doSomething(int a, Obj* obj) {
...
}

void doSomething(int a) {
   Obj tmp;
   doSomething(a, &tmp);
}

Upvotes: 6

Related Questions