I was wondering if anybody can point to a post, pdf, or excerpt of a book containing the rules for C++ variable life-times and best practices for passing and returning function parameters. Things like when to pass by value and by reference, how to share ownership, avoid unnecessary copies, etc. This is not for a particular problem of mine, I’ve been programming in C++ for long enough to know the rules by instinct, but it is something that a lot of newcomers to the language stumble with, and I would be glad to point them to such a thing.
2
Here’s the rules in a summary post:
- pass-by-value + copying is related + slicing
- pass-by-reference + polymorphism is related
- ownership passing is (usually) done via pointers.
- sizeof(T) is compile-time constant, making all c++ types have compile-time size
- ownership sharing via shared_ptr
- never pass ownership -style
- escaping from function local scope to upper scope requires copying the data, because the local scope data storage disappears after function call ends.
- call stack is one path in a tree; function call is moving to a subtree
- User-defined types are special – order of classes in header file is important for inheritance and composition – class scope lifetime can be tied to either heap or stack
- Polymorphic factory usually uses ownership passing; but can also be implemented using copying/clone and pass-by-reference.
- Avoiding unnecessary copies is bad practise – copying should be supported for all data.
- Interfaces only support passing compile-time amount of data through the interface. All data needs to be split to small pieces; and dynamic amount of it requires repeated function calls to the interface.
- Constructor parameters allow adding parameters to object
- All heap allocation in arrays is outside of the type system — there does not exists type that can contain dynamic amount of memory inside it.
1