mardi 30 août 2022

What happens to a temporary named object when it is returned and used in initialisation? [duplicate]

If I have a class below which has standard constructors and desturctor

class A {
 private:
  int data
 public:
 //normal constructor 
  A(int other)

 //move constuctor
  A(A&& other)
 
 //move operator
  A& operator=(A&& other)
 
 //copy constructor
  A(const A& other)

 //copy assignment operator
  A& operator=(const A& other)
 
 //destrcutor
 ~A()

}

What happens when I return an object from a function and use that as a constructor? Is the copy constructor called on the return of the function and a new object created? And is the destructor for the temporary object in the function called when the function call ends?

A initialise(bool b){
 if(b==true){
   A Temp1(1)
   return Temp1
   }
  else{
   A Temp2(2)
   return Temp2
   }
  }

int main(){
 A a(initialise(true));
}

Aucun commentaire:

Enregistrer un commentaire