On Tue, 9 Jun 2015 14:44:57 -0700 (PDT), fl <
rxj...@gmail.com> wrote:
>
>Hi,
>
>There is an on-line post, which says that following code fails in case of
>self-assignment. I run it on MSVC, but do not find any failure yet. I have
>tried n=0 and n=10 two cases.
>
>What is wrong with my comprehension on this code?
>
>
>Thanks,
>
>
>
>
>////////////
>class array {
> int tmp;
>
> int *data;
> size_t n;
>public:
> array(){
> n=0;
> data=new int[n];
> }
> array &array::operator =(const array &rhs);
>};
>
>array &array::operator =(const array &rhs)
>{
> delete[] data;
At this point, you can't access anything data points to, so you might
as well set it to, say, the null pointer:
data = 0;
Try self- assignment now, and see what happens.
>
> n = rhs.n;
> data = new int[n];
> std::copy_n(rhs.data, n, data);
>
> return *this;
>}
>
>int main () {
> array a0;
> array b0;
>
> a0=a0;
> return 0;
>}
Louis