Some random hints if you get started (in my case restarted) with C++ – let me know if I wrote something in wrong in my personal memos:
- Use RAII: Resource Acquisition Is Initialization
- Use scoped variables which gets destroyed automatically after leaving the block:
MyClass myVar("Hello Memory"); - To use call by reference use the method declaration. But it might be that you are optimizing it when not necessary. Read about Want Speed? Pass by Value.
void myMethod(MyClass& something)
- Understand The Rule of three: If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them. More C++ Idioms
- Understand and avoid traps, understand shallow references.
- Understandheap vs. stack allocation. E.g. also that heap allocation times are much slower than allocations off the stack.
- Use heap allocation when you dynamically want to change memory usage of an object
- … or prefer stl (e.g. vector)
- … or when an object should be used outside of a method scope:All dynamically allocated memory must be released before the pointer (except smart pointers) pointing to it goes out of scope. So, if the memory is dynamically allocated for a variable within a function, the memory should be released within the function unless a pointer to it is returned or stored by that function.
- The = operator in auto_ptr works in a different to normal way!
- Read the FAQ or this light-FAQ
- oh my: auto_ptr, shared_ptr, smart_ptr, …!!?
- Here is a nice compilation of common possible pitfalls.
… but I’m still fighting a bit to understand the memory management problematic:
1. Are there some rules of thumb?
E.g.
- use RAI
- if you cannot apply rule 1. use shared_ptr
- if you cannot apply rule 1. use new + delete?
2. And how can I solve the problem in C++ when I return a local constructed object (via new) in Java?
E.g. the factory pattern there can look like
public static MyClass createObj() {
return new MyClass()
}
3. And how would you e.g. put a vector with a lot of data into a different variable?
Can I rely on the ‘Pass by Value‘ thing which boost performance? Should I use tmpVectorObj.swap(vectorObj2) ?
4. How would you fill a vector within a method?
This is forbidden I think:
// declare vector<Node> vectorObj in the class
void addSomething(string tmp) {
Node n(tmp);
vectorObj.add(n);
}
5. What are the disadvantages of boosts smart pointers?