I have an automatic pointer implementation:
template <typename T, bool Arr = false>
class GAutoPtr
{
T *Ptr;
public:
typedef GAutoPtr<T, Arr> &AutoPtrRef;
GAutoPtr(T *ptr = 0)
{
Ptr = ptr;
}
GAutoPtr(AutoPtrRef p)
{
Ptr = p.Release();
}
~GAutoPtr() { Empty(); }
operator T*() { return Ptr; }
T *Get() { return Ptr; }
T *operator->() const { LgiAssert(Ptr); return Ptr; }
inline void Empty()
{
if (Arr)
delete [] Ptr;
else
delete Ptr;
Ptr = 0;
}
AutoPtrRef operator =(GAutoPtr<T> p)
{
Empty();
Ptr = p.Ptr;
p.Ptr = 0;
return *this;
}
void Reset(T *p)
{
if (p != Ptr)
{
Empty();
Ptr = p;
}
}
T *Release()
{
T *p = Ptr;
Ptr = 0;
return p;
}
};
typedef GAutoPtr<char, true> GAutoString;
typedef GAutoPtr<char16, true> GAutoWString;
And this works fine in Visual C ++ 6. However, in Visual C ++ 2005 or 2008, I cannot return an automatic pointer from a function without any errors.
eg.
GAutoString Func()
{
char *s = new char[4];
strcpy(s, "asd");
return s;
}
int main()
{
GAutoString a = Func();
}
What happens is that the compiler creates a temporary GAutoString string to store the return value for the function, and then passing it to the "a" variable on the stack, calls the T * () operator on the temp variable, and then the GAutoPtr constructor (T * ptr = 0 ) instead of using the copy constructor: GAutoPtr (AutoPtrRef p)
This causes temp auto ptr to delete the memory, and "a" holds the pointer to the freed memory.
VC6 . , , gcc Linux Mac, . VC2008 . , "const" , , ... , .
VC 2005/2008?