C++ operator overloading return pointer -


i'm new programming in c++ , wondering something:

whenever see operator overloading in c++ it's done 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 "+" operator called, creates object "stone", , returns copy of this. can't performance when dealing huge objects?

wouldn't better use dynamic memory in example below:

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

or seeing wrong?

thanks in advance

trying reason things out not particularly accurate way of estimating performance: need write program measure whether or not 1 implementation better another.

there number of ways in no copy happen @ all; named return value optimization (nrvo) , move assignment relevant ideas here.

even if decide want suggestion, shouldn't implement have, since has wrong semantics: you've had operator+ return pointer-to-thing rather thing. also, working pointers (especially bare pointers) risky, since gives lot more opportunities make mistakes.

if want implement along lines, need wrap pointer semantics in class provides value semantics.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -