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

  1. you not need ownership of object , simple alias do, in case pass const reference,
  2. you must mutate object, in case, use pass non-const lvalue reference,
  3. 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

  1. they changed inside function , such changes should reflected outside, in case pass non-const reference
  2. the function should callable without argument, in case pass pointer, users can pass null/0/nullptr instead; apply previous rule determine whether should pass pointer const argument
  3. they of built-in types, can passed copy
  4. 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

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -