The meaning of a = b in object oriented languages

Bryan Olson fakeaddress at nowhere.org
Tue Sep 18 23:44:52 EDT 2007


Jim Langston wrote:
> Assignment operators in C++ should attempt to prevent two pointers poining 
> to the same memory location.  Consier a simple class (untested):
> 
> class Foo
> {
> public:
>    char* Data;
>    int DataSize;
>    Foo( int Size ): DataSize( Size ) { Data = new char[Size]; }
>    ~Foo() { delete Data[]; }
> };

[...]
>    Foo& operator=( const Foo& rhs )
>    {
>       delete[] Data;
>       Data = new char[rhs.DataSize];
>       memcpy( Data, rhs.Data, rhs.DataSize );
>       DataSize = rhs.DataSize;
>    }
> 
> You can see that we have to manually do some things.  We have to delete[] 
> our pointer, new a new buffer, copy the cotents, copy the DataSize over, 
> none of which the default assignment operator would of done.
[...]
> Incidently, there may be errors in the code I've shown here if you attempt 
> to compile it. Be forewarned. 

There's the "self-assignment" bug. See the popular C++ FAQ.

Follow-ups to comp.lang.c++
-- 
--Bryan



More information about the Python-list mailing list