Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?

Tags:

c++

idioms

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.

like image 209
Brian R. Bondy Avatar asked Nov 16 '08 15:11

Brian R. Bondy


1 Answers

You don't need to know C++'s complicated function typedef declaration syntax. Here's a cute trick I found.

Quick, describe this typedef:

typedef C &(__cdecl C::* const CB )(const C &) const; 

Easy! CB is a pointer to a member function of class C accepting a const reference to a C object and returning a non-const reference to a C object. Oh, and it’s a const member function. Oh, and the function pointer itself is const… (Right?)

The C++ function declaration specification syntax is notoriously obtuse and hard to remember. Yes, there are tricks seasoned C++ veterans may use to decipher such horrors, but that’s not what this tip is about. This tip is about how you don’t need to remember this horrible syntax and still be able to declare such function pointer typedefs (e.g. in case you’re interacting with some legacy API that never heard of boost::function). Instead of breaking a mental sweat, let the compiler do the work for you. Next time you’re trying to create a typedef to a member function that looks like this:

struct C {         const C& Callback(const C&) const   { } }; 

Instead of struggling to manually come up with the complex syntax above, induce an intentional compilation error which will force the compiler to name the beast.

For example:

char c = &C::Callback; 

The compiler happily spews this helpful error message:

“… cannot convert from 'const C &(__cdecl C::* )(const C &) const' to 'char'” 

Which is what we’re looking for. :)

like image 87
Assaf Lavie Avatar answered Oct 07 '22 23:10

Assaf Lavie