how to call constructor explicitly

Started by
1 comment, last by Fragmo 21 years ago
I have an array class that uses malloc/realloc to allocate its memory and I need to know how to call a class constructor explicitly so I can initialize each item as its needed. Is this even possible? I have some code that initializes the items differently but the compiler spews about 30 warnings every time I compile because there''s no matching delete operator. If i can''t call the constructor explicitly how can I get rid of these warnings? c:\dev\common\arrayx.h(171) : warning C4291: ''void *__cdecl CArrayX::Wrapper::operator new(unsigned int,class CStr *)'' : no matching operator delete found; memory will not be freed if initialization throws an exception c:\dev\common\arrayx.h(160) : see declaration of ''new'' c:\dev\common\arrayx.h(170) : while compiling class-template member function ''void __thiscall CArrayX::SetAtIndex(long,class CStr &)'' here''s some of the code in question: class CArray { ... long m_lSize; T* m_pItems; long Add(T& item) { CheckRealloc(1); if (m_lSize < m_lAlloc) { SetAtIndex(m_lSize, item); ++m_lSize; return m_lSize - 1; } return -1; } class Wrapper { public: Wrapper(T& _t) : t(_t) { } template void *operator new(size_t, _Ty* p) { return p; } void operator delete(void*) { } T t; }; void SetAtIndex(long index, T& t) { new(&m_pItems[index]) Wrapper(t); }
Advertisement
Sounds like you want placement new, which constructs in a given memory location that already exists. CHeck out :c++ faq lite Or Modern C++ Design, by ALexandrescu.
cool, thanks for the link, that helped me fix it

all i needed to do to fix the warnings was add another param to the overloaded delete operator

void operator delete(void*, void* p)
{
}

This topic is closed to new replies.

Advertisement