Created
May 22, 2022 11:12
-
-
Save rahulbhadani/4bdc18992bffc0b1118777c227fe77e0 to your computer and use it in GitHub Desktop.
RAII examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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