C++: 10 Things You Need To Know

TL;DR

  1. shared_ptr is the closest thing C++ has to a Java reference
  2. use make_shared instead of new
  3. C++ does in effect have a garbage collector. Using constructors/destructors and smart pointers you can implement deterministic resource deallocation.
  4. 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.
  5. 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.
  6. I have seen different results from g++ vs clang even though g++ is alias of clang on mac. [1]
  7. 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 a vector to address this problem, but vector is not fixed-size.
  8. You cannot have a statement T& x;. You must assign it to something (p. 190 Stroustrup – read it).
  9. Do not return reference to a local variable from a function i.e., don’t do vector& f(). Instead do vector f(). And on the call site do auto 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.
  10. 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 assign v to a (non-local) variable inside the function (e.g., suppose f is a ctor and you want to assign v to a private variable; something we do commonly in Java), it will trigger a copy. The only way to protect against this is to pass a shared_ptr to f. The statement auto &z=v; (inside f) will not trigger copy but if z is private variable, you can’t do that. z has to be a local variable.

References

This entry was posted in Computers, programming, Software and tagged . Bookmark the permalink.

Leave a comment