2

For a school project, I am writing a class to store arbitrary length integers. I have an operator- for it like this:

BigInt BigInt::operator-() const {
    BigInt newNum { *this };
    newNum.m_positive = !newNum.m_positive;
    return newNum;
}

The problem with this code is that the current object gets copied twice (at line 2 and line 4). Is there any way I can avoid this?

Things that don't work:

  • Simply returning a reference to newNum: UB
  • Allocating memory with new and returning a reference to it: memory leak
  • Allocating memory and returning a (smart) pointer: Not the desired behavior for the - operator
  • Changing this and have it copied by the return statement: Can't undo the changes to this
  • 7
    *The problem with this code is that the current object gets copied twice (at line 2 and line 4)* -- How do you know this? The compiler's optimizer is smarter than you think it is. Time to introduce you to the [as-if rule](https://en.cppreference.com/w/cpp/language/as_if) – PaulMcKenzie Dec 24 '22 at 16:27
  • 3
    And you've actually verified two copies are being made or are you just guessing? – Captain Obvlious Dec 24 '22 at 16:27
  • 3
    This is untrue in modern C++17, only one copy is made. – Quimby Dec 24 '22 at 16:29
  • 5
    And even before C++17, all major compilers were smart enough to reduce the number of copies made in "release mode". – PaulMcKenzie Dec 24 '22 at 16:30
  • *Things that don't work:* -- Well, hopefully we've saved you time on not having to worry about any of this. – PaulMcKenzie Dec 24 '22 at 16:32
  • https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization – Mat Dec 24 '22 at 16:34
  • 4
    *In C++, how can I return a modified copy of the object without double copying it when overloading an operator?* -- And the answer is a funny one -- *"don't do anything"*. I know it sounds trivial, but that literally is the answer. – PaulMcKenzie Dec 24 '22 at 16:40
  • 1
    @Quimby Not _necessarily_, but it would be very surprising if NRVO didn't take effect here. – Nathan Pierson Dec 24 '22 at 17:09

1 Answers1

0

The question was answered in the comments. The code is optimized by the computer (within the boundaries of the as-if rule.

What in particular happens here is copy-elision / return value optimization as explained e.g. here on tackoverflow.

minorChaos
  • 101
  • 7
  • @DumpQuestion It is good to close the question by accepting an answer. You could also [write the asnwer yourself](https://unix.stackexchange.com/help/self-answer). – minorChaos Aug 30 '23 at 09:01
  • You could also [write the answer yourself](https://unix.stackexchange.com/help/self-answer). – minorChaos Aug 30 '23 at 09:04