1

The program

#include<iostream>

using namespace std;

struct abhi{
int a=2;
int b=1;
~abhi(){cout<<"destroyed"<<endl;}
};

void  su(int a, int b, abhi&& ptr){
cout<<"yes"<<endl;
}

int main(){
abhi ptr;
su(1,2,move(ptr));
cout<<"after"<<endl;
}

The Output

yes
after
destroyed

Shouldnt the destructor be called inside the su function as I using move to pass the ptr. I have used move operator with unique_ptr and it used to pass the ownership completely, so I am getting different result with plain pointer.

Abhinav Singh
  • 302
  • 3
  • 15
  • 1
    You are passing the object ptr by reference (rvalue reference). So neither destructor is called because the object ptr is not a temporary object. – Vlad from Moscow Jun 26 '20 at 04:41
  • @VladfromMoscow no I m passing rvalue reference so either my calling function shoud be a constant, in this case `{}` or using `move` to pass my `ptr` as rvalue – Abhinav Singh Jun 26 '20 at 04:48
  • Moving a `unique_ptr` doesn't call its destructor. Whatever you were observing wasn't that. – chris Jun 26 '20 at 04:52
  • @chris I m not telling move will call the destructure of a `unique_ptr` but it will pass the ownership to the caller function and when that called function is finished then the destructor of that moved unique_ptr will be called, but in this case I m not seeing this.Is it due to fact that I using stack allocated variable `ptr` and not a pointer? – Abhinav Singh Jun 26 '20 at 04:57
  • 1
    I'm not understanding why you expect moving your own type to call its destructor then. What does it mean for ownership of your type to transfer? And Vlad's point still applies: `std::move` doesn't immediately move, it just casts to an rvalue reference, so the object really is being passed by reference here. (Move operations are also disabled entirely for your type because you spelled out its destructor.) – chris Jun 26 '20 at 05:01
  • @chris okay I think I got this, thanks :) – Abhinav Singh Jun 26 '20 at 05:09
  • 1. Rule of Five. 2. Std::move doesn't move, it is just a way to case a value to an 'rvalue-ref', at one point it was proposed to be called 'rvalue_cast`. 3. Learn about scope. – Waqar Jun 26 '20 at 05:55
  • 1
    Does this answer your question? [What is std::move(), and when should it be used?](https://stackoverflow.com/questions/3413470/what-is-stdmove-and-when-should-it-be-used) – Lukas-T Jun 26 '20 at 06:13

0 Answers0