Reputation: 89
I have a question about default arguments in c++. If I a have a function like this:
int foo(int* obj = new Int(4)) {
/* Stuff with obj. */
}
Now, of course, the integer is here just used as an example, but the question is if I were to provide a value for the argument like this:
int x = 2;
foo(&x);
will the expression obj = new Int(4)
still be evaluated even though I provided a value for the argument and therefore allocated memory which I then can't read from anymore?
Upvotes: 2
Views: 777
Reputation: 36617
Using a new
expression as a default value for an argument, as in
int foo(int *obj = new int(4));
is an extremely bad idea, since there are possible use cases that behave inconsistently with each other, and a number of bad possible outcomes.
Let's say, for sake of discussion that the implementation of foo()
does
delete obj;
That is okay if the caller does either of
foo(); // default argument is a new expression
foo(new int(2));
but causes undefined behaviour if the caller does one or more of;
foo(&some_int); // some_int is a variable local to the caller
foo(new int[2]); // dynamically allocates an array
Conversely, let's say that foo()
does NOT do delete obj
. In this case, either of these statements
foo();
foo(new int(3));
foo(new int [2]); // dynamically allocates an array
cause a memory leak, and
foo(&some_int);
will probably work correctly (assuming foo()
does not invoke undefined behaviour in other ways).
The real problem is that foo()
has no way (within bounds of standard C++) of detecting which of the above the caller does. So there is a real risk of either undefined behaviour or a memory leak, unless the caller does EXACTLY the "right thing" (where "right thing" means not causing a memory leak or undefined behaviour). And, since there are more options to do the wrong thing, odds are the caller will NOT do exactly the right thing. Bear in mind that programmers are notoriously terrible at reading documentation, so relying on documentation is a poor way to ensure the caller (or the programmer writing code in the caller) does what is needed to avoid problems like the above.
Upvotes: 5
Reputation: 96845
No, default arguments are only used when there is no argument passed to them. new
won't be invoked and thus there will be no memory allocation. Also, as Some programmer dude said you have a memory leak if you do not clean up at some point either inside (or outside) the function body.
Upvotes: 2