Monday 15 April 2013

c++ - The object is destroyed before being returned -


I do not understand that when my method returns an object, the object will be destroyed.

Post class structure and methods here.

  Class Var {public: var operator = = (Constant & amp; var); Private: Action / Operation (Var * var, VAR_OPERATOR ops); }   

method:

  var :: operator = = (on the console) & var {var tmp = this- & gt; _operation ((* *), VAR_ADD); Return TMP; // Here TMP variable is zero var var :: _ operation (Var * var, VAR_OPERATOR op) {Var tmp; // Operation // Here is the tmp return value in the tmp variable; }   

Why do anyone know?

TMP warrant is present in it ... then it exists within operator + = and _ operation Is when the TMP is out of the scope, then the destroyer is called. The correct way to do this is:

  WAR and amp; Var :: operator = = (constant war and war) {_operation (*, and, var, * this, VAR_ADD); Return * This; } Void :: _ Operation (Constable and LHS, Constant & amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; Res; VAR_OPERATOR ops) {res == ... // Operations // here of TMP variable With the value}   

+ = With the operator we mean that internal data will change (in this case * this + = val), so there is no return type, or if we * Can return to status:

  (v + = val) - val2; In   

v + = val is called operator + = and the second return is changed, now if we define - Operators like friends val operator - (Constal L & H, Kontol & amp; amp; rhs) We may have compressed expressions.

What you are trying to do is:

  Wind :: Operator + (Constant and Var 1, Const. Ver, and Work 2) {TMP TMP ; // Internal Content Return TMP; }   

This operator can now be a friend

  Friends Vir Operator + (Constant and Var 1, Const War and Work 2) {TMP TMP ; // Internal Content Return TMP; }   

This is still wrong because we need to define the copy constructor and the essence operator! Because it is true that the temporary will be destroyed but before we can call the copy maker (or the ASSIGNMENT operator) in a way that we can be a "clone".

All modern C ++ compiler RVO (Return Value Optimization) but this is another story.

No comments:

Post a Comment