Skip to content

Instantly share code, notes, and snippets.

@rahulbhadani
Created May 22, 2022 11:12
Show Gist options
  • Save rahulbhadani/4bdc18992bffc0b1118777c227fe77e0 to your computer and use it in GitHub Desktop.
Save rahulbhadani/4bdc18992bffc0b1118777c227fe77e0 to your computer and use it in GitHub Desktop.
RAII examples
// OPTION 1
class Object
{
private:
int* data;
public:
Object(const int size)
{
data = new int[size];
} // Acquisition
~Object()
{
delete[] data;
} // release
};
void myFunc()
{
Object P(10); // lifetime gets automatically associated to enclosing scope
}// automatically destroys and deallocate for P and P.data
// OPTION 2
#include <memory>
class Object
{
private:
std::unique_ptr<int> data;
public:
Object(const int size)
{
data = std::make_unique<int>(size);
}
};
void myFuc()
{
Object P(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment