Created
February 8, 2023 21:33
-
-
Save leonardopsantos/425332d591544f286fd14d5b98433bfa to your computer and use it in GitHub Desktop.
C++ RAII made simpler by using smart pointers
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
/* | |
# C++ RAII example | |
Compile with: | |
```sh | |
$ g++ -Wall -O3 -g -o raii raii.cpp | |
``` | |
Valgrind: | |
```sh | |
$ valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all --track-origins=yes ./raii | |
==52320== Memcheck, a memory error detector | |
==52320== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. | |
==52320== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info | |
==52320== Command: ./raii | |
==52320== | |
Foo = 10 | |
Bar = 10 | |
Data = 10 | |
==52320== | |
==52320== HEAP SUMMARY: | |
==52320== in use at exit: 4 bytes in 1 blocks | |
==52320== total heap usage: 5 allocs, 4 frees, 73,760 bytes allocated | |
==52320== | |
==52320== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 | |
==52320== at 0x483BE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) | |
==52320== by 0x109193: Foo (raii.cpp:12) | |
==52320== by 0x109193: main (raii.cpp:60) | |
==52320== | |
==52320== LEAK SUMMARY: | |
==52320== definitely lost: 4 bytes in 1 blocks | |
==52320== indirectly lost: 0 bytes in 0 blocks | |
==52320== possibly lost: 0 bytes in 0 blocks | |
==52320== still reachable: 0 bytes in 0 blocks | |
==52320== suppressed: 0 bytes in 0 blocks | |
==52320== | |
==52320== For lists of detected and suppressed errors, rerun with: -s | |
==52320== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) | |
``` | |
*/ | |
#include <cstdio> | |
#include <memory> | |
struct Data { | |
int value; | |
}; | |
class Foo { | |
public: | |
Foo() | |
{ | |
this->my_foo = new Data(); | |
} | |
void set(int v) | |
{ | |
this->my_foo->value = v; | |
} | |
int get() | |
{ | |
return this->my_foo->value; | |
} | |
protected: | |
Data *my_foo; | |
}; | |
class Bar { | |
public: | |
Bar() | |
{ | |
this->my_bar = std::shared_ptr<Data>(new Data()); | |
} | |
void set(int v) | |
{ | |
this->my_bar->value = v; | |
} | |
int get() | |
{ | |
return this->my_bar->value; | |
} | |
std::shared_ptr<Data> get_data() | |
{ | |
return this->my_bar; | |
} | |
protected: | |
std::shared_ptr<Data> my_bar; | |
}; | |
int main( void ) | |
{ | |
Foo foo; | |
foo.set(10); | |
printf("Foo = %d\n", foo.get()); | |
Bar bar; | |
bar.set(10); | |
printf("Bar = %d\n", bar.get()); | |
std::shared_ptr<Data> d = bar.get_data(); | |
printf("Data = %d\n", d->value); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment