pointers - How to pass objects to functions in C++? -
i new c++ programming, have experience in java. need guidance on how pass objects functions in c++.
do need pass pointers, references, or non-pointer , non-reference values? remember in java there no such issues since pass variable holds reference objects.
it great if explain use each of options.
rules of thumb c++11:
pass by value, except when
- you not need ownership of object , simple alias do, in case pass
const
reference, - you must mutate object, in case, use pass non-
const
lvalue reference, - you pass objects of derived classes base classes, in case need pass reference. (use previous rules determine whether pass
const
reference or not.)
passing pointer virtually never advised. optional parameters best expressed boost::optional
, , aliasing done fine reference.
c++11's move semantics make passing , returning value more attractive complex objects.
rules of thumb c++03:
pass arguments by const
reference, except when
- they changed inside function , such changes should reflected outside, in case pass non-
const
reference - the function should callable without argument, in case pass pointer, users can pass
null
/0
/nullptr
instead; apply previous rule determine whether should pass pointerconst
argument - they of built-in types, can passed copy
- they changed inside function , such changes should not reflected outside, in case can pass copy (an alternative pass according previous rules , make copy inside of function)
(here, "pass value" called "pass copy", because passing value creates copy in c++03)
there's more this, these few beginner's rules quite far.
Comments
Post a Comment