tags:

views:

214

answers:

3

what is a temporary object? how to use it? how to use with copy constructors and destructors?

+6  A: 

The Standard doesn't define the term temporary object explicitly. However it uses the word temporaries at some places.

Temporaries are generally objects(I am not being pedantic here) without a name generally produced as a result of an expression(or a subexpression inside an expression) and generally destroyed after the completion of the expression.

Temporaries cannot attach themselves to non-constant references. So the following is illegal

  int &k= 5;  //5 is a temporary here

However temporaries can be bound to constant references because using the keyword const explicitly extends the lifetime of that temporary

  const int& k= 5; //legal

And please don't confuse between the terms rvalues and temporaries. Both are quite different.

how to use with copy constructors and destructors?

I am not sure what you actual mean by how to use.

Prasoon Saurav
A: 

You don't create nameless temporary objects, the compiler does, it can happen when

  • the code uses an object direct by just calling its constructor without assign that object to a variable.
  • When returning from a function that returns an object.
Ravi Gupta
+2  A: 
class MyClass
{
public:
  MyClass():x(0), y(0){} //default constructor
  MyClass(int X, int Y):x(X), y(Y){} //user-defined constructor
  MyClass(const MyClass& tempObj):x(tempObj.x), y(tempObj.y){} //copy constructor

private:
int x; int y;
};

int main()
{
   MyClass MyObj(MyClass(1, 2)); //Here, MyClass(1, 2) returns a temporary object which you will be passing by reference to your copy constructor.
}

You could add a destructor to see which object gets destroyed first in order but you don't have to worry about the drestruction of temporary objects since they are managed by c++ complier.

Dave18
@Dave18: You should read this: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6. Always prefer initialization list over assignment.
Prasoon Saurav