C++ compile-type resource owner assertion -



C++ compile-type resource owner assertion -

class resource; class device { ... public: resource createresource(); bindresource(const resource&); }; int main() { device dev; device oops; auto res = dev.createresource(); dev.bindresource(res); // okay; dev created resource oops.bindresource(res); // error: oops did not create resource } programme not compile

can done @ compile-time no runtime overhead , similar syntax? example, device abstraction of direct3d renderer; can't share resources, should compile time error if try.

there workaround, uses __counter__ macro. though not provided standard, msvc , gcc back upwards it. macro relates integer value, incremented every time utilize macro in translation unit. so, implementation following:

// device.h #define device device<__counter__> template<int n> class device { public: class resource{}; resource createresource() { homecoming resource(); } void bindresource(const resource&) {} };

as can see, resource class declared within device class. instances of device class should declared using device macro. now, dev , oops instanses instantiated objects of different types. dev device<0> , oops device<1>. and, respectively, res device<0>::resource, , oops can't bind it.

this approach, however, has next drawbacks (at least): 1) passing devices function arguments problem. guarantee compile-time checking, functions deal devices should templates. may lead important code bloating. 2) if declare array of device type (for example, device devices[10]), devices of same type, and, thus, able bind resources of each other. 3) __counter__ macro provides unique values through single translation unit. if declare dev @ origin of 1 translation unit , oops @ origin of sec translation unit, types equal, , oops able bind dev's resources. 4) __counter__ not provided standard.

after all, don't recommend utilize workaround, may useful educational purposes :)

c++ resources compile-time ownership

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -