Skip to content

Instantly share code, notes, and snippets.

@domiyanyue
domiyanyue / example_wrapper_raii.cpp
Last active August 22, 2020 04:01
RAII example
class WrapperA{
public:
A *p;
WrapperA(){
p = new A;
}
~WrapperA(){
delete p;
}
};
int mem_demo_static(){
A a;
return a.func();
// A's destructor is called automatically
}
int mem_demo_dynamic(){
A* a = new A;
return a->func();
// A's destructor is not called, memory leak!
class A {
public:
A(int n){
array = new int[n];
}
~A(){
delete array;
}
private:
int *array;
@domiyanyue
domiyanyue / raii_example3.cpp
Last active August 10, 2020 02:03
RAII example 3
int demo3(){
A *a = new A;
int ra = a -> func();
if(ra == 2) {
try {
B *b = new B;
}
catch (...)
{
delete a;
@domiyanyue
domiyanyue / raii_example2.cpp
Created August 10, 2020 01:40
RAII example 2
int demo2(){
A *a = new A;
int ra = a -> func();
if(ra == 2) {
B *b = new B;
int rb = b->func();
delete a;
delete b;
return rb;
@domiyanyue
domiyanyue / raii_example1.cpp
Last active August 10, 2020 01:34
RAII Example 1
int demo1(){
A *a = new A();
int r = a -> func();
delete a;
return r;
}
@domiyanyue
domiyanyue / run.txt
Last active May 9, 2020 20:52
use rpath to build
g++ main.o -L. -lmy_math -o a.out -Wl,-rpath,/home/cpp_tutorial/static_library
./a.out
0.5
@domiyanyue
domiyanyue / run.txt
Last active May 9, 2020 20:52
set LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/cpp_tutorial/static_library
./a.out
0.5
@domiyanyue
domiyanyue / run.txt
Created May 8, 2020 22:25
dynamic library run error
./a.out
./a.out: error while loading shared libraries: libmy_math.so: cannot open shared object file: No such file or directory
@domiyanyue
domiyanyue / run.txt
Created May 8, 2020 22:18
delete and run static library executable
rm libmy_math.a
./a.out
0.5