1

Coming from a more Java background I am wondering how to return a new object by reference. I want the Fraction class to be immutable, so that every operation returns a new object with the result of the operation.

This would be my code in Java:

class Fraction {
    int numerator;
    int denominator;

    // Constructor

    Fraction multiply(Fraction other) {
        return new Fraction(other.numerator * this.numerator, 
                            other.denominator * this.denominator);
    }

}

But if I would do that in C++ I would create a memory leak because I am not capable of cleaning up the initialized Fraction object, because I have only a reference to the object. So, how do I deal with this in C++?

class Fraction {
private:
    int32_t numerator;
    int32_t denominator;
 public:
    Fraction(int32_t numerator, int32_t denominator) {
        this->numerator = numerator;
        this->denominator = denominator;
    }

    Fraction& operator*(Fraction& other) {

        auto numerator = other.numerator * this->numerator;
        auto denominator = other.denominator * this.denominator;

        return *(new Fraction(numerator, denominator))
    }
};
BaCaRoZzo
  • 7,022
  • 6
  • 44
  • 72
TimKaechele
  • 500
  • 5
  • 12

2 Answers2

16

Don't use new at all, just return by value.

Fraction operator*(Fraction const& other) const
{
    auto numerator = other.numerator * this->numerator;
    auto denominator = other.denominator * this->denominator;

    return Fraction(numerator, denominator);
}

Your latter method will result in a leaked pointer. And you don't need to worry about the returned Fraction being copied thanks to return value optimization

Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
  • 3
    Plus, it makes no sense for the multiplication operator to return a reference or a pointer in the first place. – juanchopanza Sep 08 '15 at 12:28
  • Ok, thanks for the quick answer. I thought it was the default way to return a reference for the operators. – TimKaechele Sep 08 '15 at 12:33
  • 1
    @TimKaechele, you should probably mark `operator*` as being a `const` method. You don't want `x = a*b` to cause a change in `a`. Like this `Fraction operator*(Fraction const& other) const { ....` – Aaron McDaid Sep 08 '15 at 12:40
1

In C++ you have control over where you want to place your object. You can choose stack/heap as per your needs.

I dont't want to confuse you now, but you can lookup use of "placement new" if you want even more conrol over your object's place in memory.

I am not an expert in JAVA but last time I checked, you had to use new to allocate a object in java.

I think this has been explained here pretty well.When to use/not to use new in c++.

When to use "new" and when not to, in C++?

Welcome to the world of C++

Community
  • 1
  • 1
basav
  • 1,355
  • 10
  • 19
  • 2
    Just a side-note: using new in Java doesn't necessarily mean that the object will be heap-allocated. The JIT can do an escape analyzes to prove that an object is not used in an outer scope, and then allocate it on the stack. – Jens Sep 08 '15 at 12:42
  • 1
    The linked question is outdated. In C++11 as the OP uses you don't need `new` at all. – nwp Sep 08 '15 at 12:50
  • @jens amusingly, in C++, if the compiler can prove that the lifetime of the object is bounded, it can also elide the `new`. (Wording stressing this optimization is legal was even added in C++11). If it can prove that the object leaks, it can even recycle the memory on you (without calling the dtor). Neither of these are required, naturally, as the programmer can just use automatic storage. – Yakk - Adam Nevraumont Sep 08 '15 at 14:25
  • @Yakk Yes, the observable behavior is the only thing that counts, and that is surprisingly small. I just wanted to prevent the impression that Java always creates objects on the heap. I think many people assume that compilers, being JIT or traditional ones, more or less translate the code one to one, and do some simple optimizations only. Instead, the program should be seen as a semantics and the compiler generates a code program with the same semantics, but different properties. – Jens Sep 08 '15 at 15:15