The first thing that variant class must do is reserving a buffer of memory big enough to hold the largest type in the list. Fortunately, we've already written a meta-function which selects largest type: largest_type<TLIST>::type, so we can use it as following:
template<typename TLIST>
class variant {
   char _buf[sizeof(largest_type<TLIST>::type)];
}; 


As note about operator new: when we write in the code new std::string("abc") we actually ask to perform two different tasks: (1) allocate memory to hold the object; (2) initialize the object in that memory (by invoking constructor). If we already have the memory buffer, and we only want to do the initialization, the syntax would be:
new (_buf) std::string("abc");

this is called "placement operator new", and we will use it to initialize non-trivial (non-POD) types in our variant class.

Same is true for operator delete, and if we only want to invoke the destructor of the class, without memory deallocation, we can just call it as any ordinary function. So the complete code will be:
using namespace std;

char buf[sizeof(string)];
string *ps = new (buf) string("abc");
// ... use "ps"
ps->~string();

Last edited Nov 30, 2007 at 10:03 PM by migo, version 1

Comments

No comments yet.