Return copy with overloaded operators

I have a class Foofor which I overloaded the + operator as follows:

Foo Foo::operator+(const Bar &b)
{
    Foo copy = (*this);
    if (someCondition) return copy;
    //snip
}

For me it looks reasonable. However, when I return the copy, Visual Studio warns me of an error that "may be caused by heap corruption." Is there something wrong with what I did?

edit: update with additional information.

Error message:

Windows called a breakpoint in SAMPLE.EXE.

This may be due to a bunch of corruption, which indicates an error in sample.exe or any of the dlls loaded.

It could also be due to user pressing the F12 key while sample.exe has focus.

The output window may contain more diagnostic information.

Copy constructor:

Foo::Foo(const Foo&p)
{
    some_pointer = p.get_some_pointer();
    some_value = p.get_some_value();
}

The code it breaks into:

//within dbgheap.c
    extern "C" _CRTIMP int __cdecl _CrtIsValidHeapPointer(
            const void * pUserData
            )
    {
            if (!pUserData)
                return FALSE;

            if (!_CrtIsValidPointer(pHdr(pUserData), sizeof(_CrtMemBlockHeader), FALSE))
                return FALSE;

            return HeapValidate( _crtheap, 0, pHdr(pUserData) );
    }
+5
1

( frees) ( , , , ).

, , , . , :

// buggy!!!
struct test {
    int * data;
    test() : data( new int[5] ) {}
    ~test() { delete [] data; }
    test( test const & rhs ) : data( rhs.data ) {}
    test& operator=( test const & rhs ) {
       data = rhs.data;
    }
};
int main() {
    test t1;          // 5 ints allocated int t1.data
    test t2( t1 );    // no memory allocated, t2.data == t1.data
} // t2 out of scope: t2.~test() => delete t2.data
  // t1 out of scope: t1.~test() => delete t1.data but both are the same: double delete

, , . ( ) , , .

, ( ) . ( ) , , std::auto_ptr ( std::unique_ptr ++ 0x - ). boost::shared_ptr ( std::shared_ptr ++ 0x) , .

+3

All Articles