3 Replies - 231 Views - Last Post: 25 April 2012 - 10:19 PM Rate Topic: -----

#1 nunc  Icon User is offline

  • D.I.C Head

Reputation: 34
  • View blog
  • Posts: 123
  • Joined: 20-November 11

Destructors and temporary Variables

Posted 25 April 2012 - 08:53 PM

I've got an exam over this on Friday, and I'd like to make sure I know what's going on.

Assume a copy ctor is made.

demo fun(demo X){
//returning and passing new objects
   return X;

}
int main(){
    demo A;
    A = fun(A);

return 0;
}



My question is mostly in the fun method. I assume X is bounded by the scope, and am I correct in assuming a copy ctor is called at the return statement? Or is demo X created when it's passed as an argument in the main method?

If X is confined to the fun method, is a temp Demo object assigned to A in the main method? And when would that temp destructor be called?

This is rather confusing :P Any help is appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Destructors and temporary Variables

#2 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 862
  • View blog
  • Posts: 3,982
  • Joined: 09-June 09

Re: Destructors and temporary Variables

Posted 25 April 2012 - 09:09 PM

The copy constructor is invoked when you pass demo by value and also when your return a type "demo" from your function.

Quote

And when would that temp destructor be called?

The deconstructor will be called whenever your object(s) go out of scope.

This post has been edited by jjl: 25 April 2012 - 09:11 PM

Was This Post Helpful? 0
  • +
  • -

#3 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1418
  • View blog
  • Posts: 2,681
  • Joined: 30-May 10

Re: Destructors and temporary Variables

Posted 25 April 2012 - 09:09 PM

Why don't you try it?

class demo {
  public:
    demo() { cout << "ctor called" << endl; }
    ~demo(){ cout << "dtor called" << endl; }
};


Was This Post Helpful? 2
  • +
  • -

#4 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1394
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Destructors and temporary Variables

Posted 25 April 2012 - 10:19 PM

> and am I correct in assuming a copy ctor is called at the return statement

There's something called return value optimization in C++, and that optimization may remove the copy. So you can assume logically that the ctor is called, but in reality, it may not be.

> Or is demo X created when it's passed as an argument in the main method?

When you pass by value, a copy is created.

> If X is confined to the fun method, is a temp Demo object assigned to A in the main method?

As above, another temporary may not be created because of RVO. But at least one copy is going to happen in the entire sequence of steps.

This post has been edited by Oler1s: 25 April 2012 - 10:20 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1