简体   繁体   中英

Copy constructor and assignment operator both get called

I have the following program snippet:

Polynomial Polynomial:: add(const Polynomial b)
{
    Polynomial c;
    c.setRoot(internalAdd(root, c.root));
    c.setRoot(internalAdd(b.root, c.root));
    return c;
}

c = (a.add(b));

to my understanding, this code is suppose to add a and b together, then assign the resulting polynomial to c by calling the copy constructor.

however, when I actually test it,

  • c calls the copy constructor right away and tries to copy b,
  • then a and b add
  • then c tries to get the resulting polynomial via assignment operator
  • then the program crashes

what can i do to fix this?

Polynomial Polynomial::add(const Polynomial& b)
                                           ^

If you don't want the argument to be copied, pass it in as a reference as above.

This probably won't fix your crash - no way to tell what is causing that without more of your code (and some debugging on your side to pinpoint it), but it will remove the need for copy-constructing the Polynomial argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM