Temporary object returns

What is the difference between using the a "temporary object" and creating a new object on a local scope?

For example, lets say we have an Object with two int data members, and a member function called foo. What is the difference between :

1
2
3
4
5
6
// ex 1.
Object Object::foo( void ) {
    Object temp( 1, 2 );

    return temp;
}


and
1
2
3
4
5
6
7
// ex 2
Object Object:foo( void ) {

   return Object( 1, 2 );

}


As I understand it: in ex 1, an object is created in dynamic memory and given the name temp. It's assigns the data members to 4 and 7 according to the constructors.
return does it's work.

in ex 2 seems like it's doing the same with with out assigning it a name?
Last edited on
dynamic memory
No, that's stack memory. Dynamic (or heap) memory would be
Object *temp=new Object(1,2);

Both functions are equivalent in this case.
Both functions are equivalent in this case.

helios is right. Your functions both use stack allocation. Check this out, it demonstrates that heap (dynamic) memory allocation takes place in a different place than stack allocation. It also demonstrates that your two functions use the same allocation method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;

class Object
{
      public:
      Object(){cout << "creating   Object at " << this << endl;}
      ~Object(){cout << "destroying Object at " << this << endl;}
};

Object f1_stack()
{
       Object object;
       return object;
}

Object f2_stack()
{
       return Object();
}

Object * f1_heap()
{
       Object * object=new Object();
       return object;
}

Object * f2_heap()
{
       return new Object();
}

int main()
{
    //stack allocation
    f1_stack();
    f2_stack(); //same place as f1_stack()
    
    //heap allocation
    delete f1_heap();
    delete f2_heap(); //same place as f1_heap()

    cin.get();
    return 0;
}


Try removing one or both delete operators to see what happens ;)
Last edited on
Topic archived. No new replies allowed.