I am just learning C++, and I've come across the following conundrum:
As a C++ newbie, I've read that using reference instead of pointers (when possible) is generally a good idea, so I'm trying to get into the habit early. As a result, I have a lot of methods which have the general form of
void myMethod(ParamClass const& param);
Now, I'm wondering what is the best way to call these methods. Of course, each call will need a different object passed as a parameter, and as far as I know the only way to create it is the new operator, so now I'm doing the following:
myObject.myMethod(*new ParamClass(...));
While this method totally works, I'm wondering if there isn't another already-established "c++ way" of doing this.
Thanks for the help! Dan
You should try not to use
new
, to begin with, as using it brings the trouble of memory management.For your example, just do the following:
I recommend the first method (in two times) because there are subtle gotchas with the second.
EDIT: comments are not really appropriate to describe the gotchas I was referring to.
As
@Fred Nurk
cited, the standard says a few things about the lifetime of temporaries:[class.temporary]
This can lead to two subtle bugs, that most compilers do not catch:
Argyrios patched up Clang at my request so that it detects the first case (and a few more actually that I had not initially thought of). However the second can be very difficult to evaluate if the implementation of
forwarder
is not inline.