S
Stefan Arentz
To understand auto_ptr I mocked up this replacement class. This is also
basically my first usage of templates.
template<class X> class AutoPointer {
public:
AutoPointer(X* clazz)
: mClass(clazz)
{
}
~AutoPointer()
{
delete mClass;
}
X& operator*() const
{
return *mClass;
}
X* operator->() const
{
return mClass;
}
private:
X* mClass;
};
Now, I have this:
class Foo {
public:
Foo()
{
:rintf("Foo constructor\n");
}
~Foo()
{
:rintf("Foo destructor\n");
}
};
int main()
{
AutoPointer<Foo> foo = new Foo;
AutoPointer<char> bar = new char[10];
}
And that outputs the expected. Great. Heap objects that are automatically
destroyed when they go out of scope. Didn't know it would be that easy.
But, in the 'the finally debate' thread somebody gave this auto_ptr example:
std::auto_ptr<char> my_ptr(new char[987]);
Which translates to this with my template:
AutoPointer<char> bar = new char[10];
It compiles fine, which I find odd, since the template definition states:
template<class X> class AutoPointer {
^^^^^
that X should be a class right? So why does it accept a char* in this case? Is there
any way to prevent that?
S.
basically my first usage of templates.
template<class X> class AutoPointer {
public:
AutoPointer(X* clazz)
: mClass(clazz)
{
}
~AutoPointer()
{
delete mClass;
}
X& operator*() const
{
return *mClass;
}
X* operator->() const
{
return mClass;
}
private:
X* mClass;
};
Now, I have this:
class Foo {
public:
Foo()
{
:rintf("Foo constructor\n");
}
~Foo()
{
:rintf("Foo destructor\n");
}
};
int main()
{
AutoPointer<Foo> foo = new Foo;
AutoPointer<char> bar = new char[10];
}
And that outputs the expected. Great. Heap objects that are automatically
destroyed when they go out of scope. Didn't know it would be that easy.
But, in the 'the finally debate' thread somebody gave this auto_ptr example:
std::auto_ptr<char> my_ptr(new char[987]);
Which translates to this with my template:
AutoPointer<char> bar = new char[10];
It compiles fine, which I find odd, since the template definition states:
template<class X> class AutoPointer {
^^^^^
that X should be a class right? So why does it accept a char* in this case? Is there
any way to prevent that?
S.