Lifetime of temporary objects

Apr 1, 2009 at 1:28pm
I'm needing to do something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A
{
public:
  int* get() { return &v; }
protected:
  int v;
};

void foo(int* p);

int main()
{
  foo(A().get());  // is this safe?
}


The temporary object created by A() needs to live long enough for the foo() function to execute and complete, otherwise the pointer goes bad. Is this a safe assumption? Or does the A() object die before then?

If I had to guess, I would say the above is perfectly safe to do, however I figured I should ask here anyway.
Apr 1, 2009 at 1:48pm
closed account (S6k9GNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A
{
public:
  int* get() { return &v; }
protected:
  int v;
};

void foo(int* p);

int main()
{
  A myClass;
  foo( myClass.get() ) //I don't think you can call functions in the temporary variable. I may be wrong
}
Last edited on Apr 1, 2009 at 1:53pm
Apr 1, 2009 at 1:51pm
Trying it, I've seen that the A object was destructed after the function execution.
If you want to try it yourself here is the sourcecode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A
{
public:
  int* get() { return &v; }
  ~A() { cout << "No more A\n"; }
protected:
  int v;
};

void foo(int *p)
{
   cout << "Function Called!\n";
}

int main()
{
   foo(A().get());
   return 0;
}
Apr 1, 2009 at 2:40pm
It is safe.
Topic archived. No new replies allowed.