Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ garbage collection

// raii.cpp

#include <iostream>
#include <new>
#include <string>

class ResourceGuard{
  private:
    const std::string resource;
  public:
    ResourceGuard(const std::string& res):resource(res){
      std::cout << "Acquire the " << resource << "." <<  std::endl;
    }
    ~ResourceGuard(){
      std::cout << "Release the "<< resource << "." << std::endl;
    }
};

int main(){

  std::cout << std::endl;

  ResourceGuard resGuard1{"memoryBlock1"};

  std::cout << "
Before local scope" << std::endl;
  {
    ResourceGuard resGuard2{"memoryBlock2"};
  }
  std::cout << "After local scope" << std::endl;
  
  std::cout << std::endl;

  
  std::cout << "
Before try-catch block" << std::endl;
  try{
      ResourceGuard resGuard3{"memoryBlock3"};
      throw std::bad_alloc();
  }   
  catch (std::bad_alloc& e){
      std::cout << e.what();
  }
  std::cout << "
After try-catch block" << std::endl;
  
  std::cout << std::endl;

}
Comment

is there garbage collection in c++

A C++ program can contain both manual memory management and garbage collection happening in the same program. According to the need, either the normal pointer or the specific garbage collector pointer can be used. Thus, to sum up, garbage collection is a method opposite to manual memory management.
Comment

PREVIOUS NEXT
Code Example
Cpp :: google test assert exception 
Cpp :: c++ pop string from vector 
Cpp :: how to pass an array by reference in c++ 
Cpp :: move elements from vector to unordered_set 
Cpp :: Array declaration by specifying the size in C++ 
Cpp :: opencv(4.5.1) c:usersappveyorappdatalocal emp1pip-req-build-kh7iq4w7opencvmodulesimgprocsrc esize.cpp:4051: error: (-215:assertion failed) !ssize.empty() in function 
Cpp :: Character cin(userInput) in c++ 
Cpp :: c++ queue 
Cpp :: c++ catch Unhandled exception 
Cpp :: c++ classes 
Cpp :: how to find factorial of number in c++ 
Cpp :: C++ to specify size and value 
Cpp :: compare values within within a vector c++ 
Cpp :: Maximum sum of non consecutive elements 
Cpp :: c++ function pointer 
Cpp :: array of charcter c++ 
Cpp :: javascript if else exercises 
Cpp :: c++ initialize size of 3d vector 
Cpp :: error in c++ 
Cpp :: conversion of class type data into basic type data in c++ 
Cpp :: cpp algorithm iota 
Cpp :: c++ tuple push_back 
Cpp :: why the << operator is friend 
Cpp :: new expression 
Cpp :: variable modulus 5 meaning in c++ 
Cpp :: identity 
Cpp :: how to find common divisors of two numbers in cpp 
Cpp :: c plus 
Cpp :: dinamic 
Cpp :: entering char in int c++ avoid loop 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =