C++ new operator inheritance and inline data structures -


i have (c++) system has many classes have variable storage (memory) requirements. in of these cases, size of required storage known @ creation of object, , fixed lifetime of object.

i use this, instance, create "string" object has count field, followed directly actual characters, inline object.

class string { public:     size_t count;     string(size_t count, const char* text) : count(count) {/*...*/}     inline char& at(size_t index) {         return *(reinterpret_cast<char*>(this + 1) + index);     }     void* operator new (size_t size, size_t count) {         return new char[size + count * sizeof(char)];     } };  class node { public:     size_t count;     node(size_t count, ...) : count(count) {/*...*/}     inline node*& at(size_t index) {         return *(reinterpret_cast<node**>(this + 1) + index);     }     void* operator new (size_t size, size_t count) {         return new char[size + count * sizeof(node*)];     } };  // ... , several more 

i trying reduce code duplication factoring out "inline array" behavior common base class:

template<class t> class expando {     size_t count;     expando(size_t count) : count(count) {}     inline t& at(size_t index) {         return *(reinterpret_cast<t*>(this + 1) + index);     }     void* operator new (size_t size, size_t count) {         return new char[size + count * sizeof(t)];     } }; 

however, when inherit class:

class string : public expando<char> {/*...*/} 

and go create new string:

string* str = new (4) string(4, "test"); 

gcc tries use globally overloaded new operator, instead of 1 in expando:

inline void* operator new (size_t size, void* mem) { return mem; } 

now, duplicate new operator each of classes (string, node, ...), half-defeat purpose of refactoring.

is there simple solution this? i'd maintain data inline rest of class (to avoid dereferencing , heap allocation), avoid non-standard extensions (such zero-size arrays @ end of classes). @ same time, i'd reduce duplication.

have used

using expando::new 

in derived class new operator? example:

void* operator new (....) {     using expando::new;     .... } 

otherwise, if don't mind opinion, think implementation of string class way off base. have count member, no actual pointer data member point array of whatever comprise string. talk weird implementation. asking trouble maintanence developer few years down road scratch head , go: "whaaat?"


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -