Smart Pointer
When ever you create a object of class, deconstructor will be called automatically,
but when you make pointer of that class, the deconstructor won't be automatically called. So you have to use smart pointer to de-allocate the memory.
MyInt my_int(10); // This will call the destructor
MyInt *my_int = new MyInt(10); // this won't automatically call the destructor
Unique Pointer:
#include <memory>
class MyInt {
private:
int x;
public:
MyInt(int p) { x = p; }
~MyInt() {
std::cout << " deconstructor " << std::endl;
}
int getData() {
return x;
}
};
int main() {
// MyInt my_int(10);
// std::cout << "My Int " << my_int.getData() << std::endl;
std::unique_ptr<MyInt> p(new MyInt(10)); // Here the p will be created on stack not on heap
std::cout << p->getData(); // This is the one way of declaring unique pointer
std::unique_ptr<MyInt> pp = std::make_unique<MyInt>(20); // 2nd way of creating unique pointer
// p = pp // FAIL: This will fail as ownership cannot be copied
std::unique_ptr<MyInt> ppp = std::move(p); // this will move the ownership
// MyInt *my_int = new MyInt(10);
// std::cout << my_int->getData();
MyInt *in = p.get(); // returns the pointer of that pointer
MyInt *inn = p.release(); // release the pointer
std::cout << "Before finishing: " << std::endl;
return 0;
}
std::cout << "Before finishing: " << std::endl;
return 0;
}
Comments
Post a Comment