Search code examples
c++operator-overloadingdynamic-memory-allocation

C++ operator overloading return pointer


I'm fairly new to programming in C++ and I was wondering something:

whenever I see operator overloading in C++ it's done like this:

#ifndef STONE_H
#define STONE_H

class Stone {
    private:
    int weight;

    public:
    .......

    Stone operator+(const Stone& s) {
        Stone stone;
        stone.weight = this->weight + s.weight;
        return stone;
    }

    .......
}


#endif

But when the "+" operator is called, it creates an object "stone", and returns a copy of this. This can't be good for performance when dealing with huge objects?

Wouldn't it be better to use dynamic memory for this as in the example below:

Stone * operator+(const Stone& s) {
    Stone * stone = new Stone;
    stone->weight = this->weight + s.weight;
    return stone;
}

Or am I seeing this wrong?

Thanks in advance


Solution

  • Trying to reason things out is not particularly accurate way of estimating performance: you need to actually write a program to measure whether or not one implementation is better than another.

    There are a number of ways in which no copy will happen at all; the named return value optimization (NRVO) and move assignment are relevant ideas here.

    Even if you decide that you want to do something like your suggestion, you shouldn't implement it as you have, since it has the wrong semantics: you've had operator+ return a pointer-to-thing rather than a thing. Also, working with pointers (especially bare pointers) is risky, since it gives you a lot more opportunities to make mistakes.

    If you want to implement something along those lines, you need to wrap the pointer semantics in a class that provides value semantics.