Using yasper
Initializing yasper pointers
#include "yasper.h" using yasper::ptr; struct SomeClass { SomeClass() : x(0) {} int x; int f() { return x; } }; int main(int argc, char* argv[]) { //preferred ptr<SomeClass> p1(new SomeClass); //less safe ptr<SomeClass> p2 = new SomeClass; //unsafe but still allowed SomeClass* raw = new SomeClass; ptr<SomeClass> p3(raw); return 0;
/* when program quits p1, p2, p3 all delete objects they point to */
Once you've created a smart pointer, use it as you would a regular C++ pointer. Access data members and methods with the dereferencing operator:
//access data member x cout << endl << p1->x; //call SomeClass::f cout << endl << p1->f();
You can check if a ptr is valid either by calling ptr::IsValid() or allowing the pointer to implicitly convert to a boolean.
//this works if (p1.IsValid()) cout << "Pointer is valid!"; //this also works if (p1) cout << "Pointer is still valid!";
Yasper allows for some dangerous features, so watch out and don't use them unintentionally:
long num = &someObject; //assignment to long int allowed! p1 = num;
/* Setting pointer to 0 releases it. Upon release, the object p1 points to will be deleted, p1 will become invalid */
p1 = 0; //this will not print if (p1) cout << "Still valid!"; //this will print if (!p1) cout << "Null pointer!";