Saturday, June 25, 2016

When auto fails

Got this from the book "Effective modern C++" by Scott Meyers (2014).

The book recommends the use of auto instead of explicit types. He does warn against using auto when proxy classes are involved. One example is std::vector<bool>. Using the operator[] on a std::vector<bool> yields a std::vector<bool>::reference (a proxy class) instead of a simple bool.

Consider this example:

 According to Meyers, std::vector<bool>::reference is a class (a proxy class) that contains a pointer to a word (probably a 32-bit or 64-bit memory location) that contains the boolean value. The class also contains the offset within the word to be able to locate the boolean value.

So in the example, in line 22, b is of type std::vector<bool>::reference which contains a pointer to some memory location. Note, however, that features() returns a temporary std::vector<bool> which goes out of scope as soon as line 22 finishes execution. Thus, after line 22 is executed, the word (memory location) which contains the boolean goes out of scope. The pointer within b then becomes a dangling pointer pointing to who knows what.

When the code is executed:

nonbonding@castor-ub:~/dnonbonding/tmp/auto$ g++ -std=c++11 c.cpp && ./a.out
0/100

If line 23 is executed instead of line 22:

nonbonding@castor-ub:~/dnonbonding/tmp/auto$ g++ -std=c++11 c.cpp && ./a.out
100/100

Meyers calls the style used in line 23 as "the explicitly typed initializer idiom".

No comments:

Post a Comment