Re: Calling a constructor from template class



FredsFriend wrote:
Hi,

I have a template class defined something like the following.

template <typename T>
class ArrayClass


I want this class to call the constructor on a peice of memory
multiple times (so as to reuse the memory for different objects).
The code to do this not using a template looks like this.

struct TempStruct
{
TempStruct() : i(0) { }
int i;
};

TempStruct t;
t.TempStruct::TempStruct();


One would assume that the way to use this in a template would be



template <typename T>
class ArrayClass
{
T t;
void RunConstructor()
{
// t.T::TempStruct(); // ignore this line for a bit // line one
t.T::T(); // line two
}
};

However this gives you a compiler error


if you uncomment line one and comment out line two you don't get a
compiler error (when using TempStruct as the template argument).
However this defeats the purpose of using the template so is not a
good solution.

Note the destructor works correctly using the syntax.
t.T::~T();


Any help would be appreciated, I can't seem to find anything doing
this or any help else where.

You're trying to exploit a bug (or extension - you pick) in VC++ that allows
you to invoke a constructor by name. According to the C++ standard, a
constructor does not have a name (for linkage purposes) and cannot be found
by name lookup.

What you need to do to be standard compliant is to use "placement new" to
invoke the constructor:

#include <new>

template <typename T>
struct ArrayClass
{
T t;
void RunConstructor()
{
new (&t) T();
}

void RunDestructor()
{
t.T::~T();
}
};

void f()
{
ArrayClass<int> ai;
ai.RunConstructor();
ai.RunDestructor();
}

Destructors, on the other hand, have names and can be found by name lookup,
so directly invoking the destructor by name is both legal and correct in
this instance.

-cd


.



Relevant Pages