c++ - Passing argument from heap to function -
here question. have pointer allocated memory class:
class *pclass = new class();
now want pass object function, wich use object copy , not modify it. question how correctly pass object?
void somefunc (const class &_class); { class *pclassinfunc = new class (_class); ... } ... somefunc (*pclass)
or
void somefunc (const class *_class); { class *pclassinfunc = new class (*_class); ... } ... somefunc (pclass)
or
void somefunc (class _class); { // use _class since it's copy ... } ... somefunc (*pclass)
i've choosed first way, looks strange me, smth tells me it's not correct. second 1 looks more c-style (or not?). , last 1 creates copy in stack, not desireable. so, best solution? thank answers.
edit: saw, forgot * before pclassinfunc. corrected, sorry.
i vote last approach. design function doesn't care how calling code allocated object. if wants copy, take object value. makes intentions clearer user.
it allows caller move object if don't need more. if take reference const
, then copy it, wouldn't option (you can't move const
object).
if calling code can, should avoid dynamically allocating object in first place. then, if choose take argument value, simple pass object.
Comments
Post a Comment