Thread: Weird copy assignment code

  1. #1
    Registered User
    Join Date
    Dec 2019
    Posts
    5

    Weird copy assignment code

    Code:
        vector& operator=(const vector& a){
            double *p=new double[a.sz];
            copy(a.elem, a.elem+a.sz, elem);
            delete[] elem;
            elem=p;
            sz=a.sz;
            return *this;
        }
    In chapter 17 were trying to replicate std vector.
    Why does it delete elem after it copies to elem? I dont get it

  2. #2
    Registered User
    Join Date
    Aug 2019
    Location
    inside a singularity
    Posts
    308
    Exception safe assignment – Vorbrodt's C++ Blog

    You delete after you copy so that if the copy assignment throws an exception, no change occurs or affects your original variable.

    EDIT:

    Looked at John's reply and realised I didn't look at your code correctly. If everything was written right, like John mentions to change elem to p in the copy, then you can consider my response valid.
    Last edited by Zeus_; 12-14-2019 at 11:02 AM.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook, The Wizardry Compiled

  3. #3
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    The error is that it's copying to elem instead of p. Change it to p.

    BTW, "chapter 17" is not some kind of universal reference. There's a lot of books out there!
    A little inaccuracy saves tons of explanation. - H.H. Munro

  4. #4
    Registered User
    Join Date
    Dec 2019
    Posts
    5
    Thx it works now
    author made a typo

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. copy assignment of polymorphic classes
    By skewray in forum C++ Programming
    Replies: 11
    Last Post: 03-19-2016, 11:32 AM
  2. Copy assignment help.
    By darren78 in forum C++ Programming
    Replies: 2
    Last Post: 08-08-2010, 06:21 AM
  3. question about copy constructor and assignment operator
    By sugarfree in forum C++ Programming
    Replies: 8
    Last Post: 04-20-2010, 08:39 AM
  4. Exception-Safe Copy Assignment
    By George2 in forum C++ Programming
    Replies: 22
    Last Post: 04-02-2008, 05:43 AM
  5. Copy Assignment :: C++
    By kuphryn in forum C++ Programming
    Replies: 3
    Last Post: 03-12-2002, 08:58 AM

Tags for this Thread