CS253

CS253: Software Development with C++

Spring 2017

Copy Elision

See this page as a slide show

Copy Elision

CS253 Copy Elision

Elision

The word “elision” means “omission”, like how the two-syllable “do not” becomes the one-syllable “don’t”, or Captain Kirk never seems to brush his teeth. It’s not necessary to show everything.

The Loud Class

class Loud {
  public:
    Loud() { cout << "ctor\n"; }
    Loud(const Loud &) {
        cout << "copy ctor\n";
    }
    Loud &operator=(const Loud &) {
        cout << "assign\n"; return *this;
    }
    ~Loud() { cout << "dtor\n"; }
};

int main() {
    Loud alpha;
}
ctor
dtor

No surprise, here. alpha got created & destroyed.

More Construction

class Loud {
  public:
    Loud() { cout << "ctor\n"; }
    Loud(const Loud &) {
        cout << "copy ctor\n";
    }
    Loud &operator=(const Loud &) {
        cout << "assign\n"; return *this;
    }
    ~Loud() { cout << "dtor\n"; }
};

int main() {
    Loud beta, gamma;
}
ctor
ctor
dtor
dtor

Sure.

Copy ctor & assignment

class Loud {
  public:
    Loud() { cout << "ctor\n"; }
    Loud(const Loud &) {
        cout << "copy ctor\n";
    }
    Loud &operator=(const Loud &) {
        cout << "assign\n"; return *this;
    }
    ~Loud() { cout << "dtor\n"; }
};

int main() {
    Loud delta;
    Loud epsilon(delta);
    delta=epsilon;
}
ctor
copy ctor
assign
dtor
dtor

As expected.

More copying

class Loud {
  public:
    Loud() { cout << "ctor\n"; }
    Loud(const Loud &) {
        cout << "copy ctor\n";
    }
    Loud &operator=(const Loud &) {
        cout << "assign\n"; return *this;
    }
    ~Loud() { cout << "dtor\n"; }
};

Loud foo() {
    Loud zeta;
    return zeta;
}

int main() {
    Loud eta(foo());
}
ctor
dtor

Hey, wait. Where’s the copy ctor?

Ludicrous copying

class Loud {
  public:
    Loud() { cout << "ctor\n"; }
    Loud(const Loud &) {
        cout << "copy ctor\n";
    }
    Loud &operator=(const Loud &) {
        cout << "assign\n"; return *this;
    }
    ~Loud() { cout << "dtor\n"; }
};

int main() {
    Loud theta = Loud(Loud(Loud(Loud(Loud()))));
}
ctor
dtor

There should be more than that.

Elison

Loud foo() {
    Loud iota;
    return iota;
}

int main() {
    Loud kappa(foo());
}

Modified: 2017-04-30T12:28

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building