What are some C++ related idioms, misconceptions, and gotchas that you’ve learnt from experience?
An example:
class A { public: char s[1024]; char *p; A::A() { p = s; } void changeS() const { p[0] = 'a'; } };
Even know changeS is a const member function, it is changing the value of the object. So a const member function only means that it will treat all variables as const, and it does not mean that it will actually keep all members const. (why? the const keyword on the member function treats char *p; as char * const p; And not as const char *p;
Which therefore means that p can’t point to something else. And not that you can’t change p’s data.
I’ve liked this since the time i’ve discovered it in some code:
or if you don’t have a condition at hand, you can just do
The following is attributed to @Josh (see comments). It uses the comma operator instead: