c++ - Dangling pointer with explicit conversion -


in scott meyrses effective c++ provided exampple of bad usage of implicit conversions along raii classes:

class font { // raii class public:     explicit font(fonthandle fh) // acquire resource;         : f(fh) // use pass-by-value, because     {} // c api     ~font() { releasefont(f ); } // release resource     ... // handle copying (see item14) private:     fonthandle f; // raw font resource }; 

and implicit conversion function:

class font { public:     ...     operator fonthandle() const // implicit conversion function     { return f; }     ... }; 

he provided example of such bad usage:

font f1(getfont()); ... fonthandle f2 = f1; // oops! meant copy font                     // object, instead implicitly                     // converted f1 underlying                     // fonthandle, copied 

and here said:

now program has fonthandle being managed font object f1, fonthandle available direct use f2. that’s never good. example, when f1 destroyed, font released, and f2 dangle.

why f2 dangle? after copying fonthandle resource containing in f1 f2, f2 , f1 independent objects. so, if release f1 how afffect f2? apply copying, not moving.

fonthandle pointer itself. f2 copy of pointer outside of confines of raii class. when f1 goes out of scope, free memory pointed @ fonthandle in f1...but f2 still points it.

the "fonthandle" moniker being used clarity, lots of time these c apis, separate out , hide implementation, have api functions take void pointer (void*) guts of api has information dereference , use. may typedef void *fonthandle know void pointer semantically represents.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -