TL;DR
shared_ptris the closest thing C++ has to a Java reference- use
make_sharedinstead ofnew - C++ does in effect have a garbage collector. Using constructors/destructors and smart pointers you can implement deterministic resource deallocation.
- the main thing to be wary of when writing code in C++ is not accidentally triggering expensive copy operations on big objects like collections. it requires careful coding as vectors etc. don’t output any warning message when they are being copied. It would be nice to have a static code analyzer that can warn of unwanted copy operations happening in the background.
- I have seen C++ compiler silently ignoring dead code from compilation. I was writing my program and wrote hundreds of lines without compiler error. Then the moment I started actually calling the code, I was greeted to errors.
- I have seen different results from
g++vsclangeven thoughg++is alias ofclangon mac. [1] - In C++ you cannot create a (fixed-size) array (
T[n]) whose size is not known at compile time (the size is known at runtime). This is something we take for granted in Java. And the thing that is really annoying is that the compiler does not complain, but at runtime you get a segfault. In C++, you have to use avectorto address this problem, butvectoris not fixed-size. - You cannot have a statement
T& x;. You must assign it to something (p. 190 Stroustrup – read it). - Do not return reference to a local variable from a function i.e., don’t do
vector& f(). Instead dovector f(). And on the call site doauto x = f(). C++ will do the right thing and there won’t be unnecessary copying. This is known as named return value optimization. Also see this. - Passing an object by reference to a function i.e.,
f(vector & v)gives you a first line of defense against unwanted copying, but remember if you assignvto a (non-local) variable inside the function (e.g., supposefis a ctor and you want to assignvto a private variable; something we do commonly in Java), it will trigger a copy. The only way to protect against this is to pass ashared_ptrtof. The statementauto &z=v;(insidef) will not trigger copy but ifzis private variable, you can’t do that.zhas to be a local variable.