Object backing the pointer will be destroyed at the end of the full-expression

In C++, when an object is created in a full-expression (typically, within the scope of a single statement), the object’s lifetime is limited to that full-expression. This means that the object’s destructor will be called and the memory occupied by the object will be released once the full-expression ends.

Let’s take a look at an example to understand this concept better:


#include <iostream>

class MyClass {
public:
  MyClass() {
    std::cout << "Constructor called" << std::endl;
  }
  
  ~MyClass() {
    std::cout << "Destructor called" << std::endl;
  }
};

int main() {
  std::cout << "Before object creation" << std::endl;
  
  {
    std::cout << "Inside full-expression" << std::endl;
    
    MyClass obj; // Object created within the full-expression
    
    std::cout << "End of full-expression" << std::endl;
  }
  
  std::cout << "After full-expression" << std::endl;
  
  return 0;
}
  

The output of this program will be:


Before object creation
Inside full-expression
Constructor called
End of full-expression
Destructor called
After full-expression
  

As you can see, the constructor of the object is called when it is created within the full-expression, and the destructor is called when the full-expression ends. In this case, the full-expression is defined by the curly braces ({}) surrounding the creation of the object.

It’s important to note that if an object is created outside of a full-expression (i.e., within a block of code without surrounding curly braces), its lifetime will extend beyond the block of code. In such cases, the object will not be destroyed until the scope in which it was created ends.

Read more

Leave a comment