Auto Pointer Designer in VC2008

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();
    /// a.Ptr is now garbage
}

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?

+3
2

g++? MacBook Pro :

xxx.cpp: In function ‘AutoString func()’:
xxx.cpp:52: error: no matching function for call to ‘AutoPtr<char, true>::AutoPtr(AutoString)’
xxx.cpp:12: note: candidates are: AutoPtr<T, isArray>::AutoPtr(AutoPtr<T, isArray>&) [with T = char, bool isArray = true]
xxx.cpp:9: note:                 AutoPtr<T, isArray>::AutoPtr(T*) [with T = char, bool isArray = true]
xxx.cpp:52: error:   initializing temporary from result of ‘AutoPtr<T, isArray>::AutoPtr(T*) [with T = char, bool isArray = true]’

, , - const, . Herb Sutter - GotW. std::auto_ptr . , Boost.SmartPtr. , .

Boost - , std::auto_ptr std::auto_ptr_ref. , , , auto-ptr. , , . IIRC, Josuttis ': ++. , .

+1

, T * "". , , . , , . , :

GAutoString Func()
{
    char *s = new char[4];
    strcpy(s, "asd");
    return GAutoString(s);
}

, , , .

+1

Source: https://habr.com/ru/post/1706363/


All Articles