shared_ptr :
Definition: Wraps a reference-counted smart pointer around a dynamically allocated object.
Syntax
template
class shared_ptr;
The shared_ptr class defines an object that uses reference counting to manage resources. A shared_ptr object effectively holds a pointer to the resource that it owns or holds a null pointer. A resource can be owned by more than one shared_ptr object; when the last shared_ptr object that owns a particular resource is destroyed, the resource is freed.
A shared_ptr stops owning a resource when it is reassigned or reset.
Reference Counting: It is a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources. An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of shared_ptr have been deleted.
So, we should use shared_ptr when we want to assign one raw pointer to multiple owners.
Example:
// C++ program to demonstrate shared_ptr
#include
#include
using namespace std;
class A
{
public:
void show()
{
cout<<"A::show()"<
}
};
int main()
{
shared_ptr p1 (new A);
cout << p1.get() << endl;
p1->show();
shared_ptr p2 (p1);
p2->show();
cout << p1.get() << endl;
cout << p2.get() << endl;
// Returns the number of shared_ptr objects
//referring to the same managed object.
cout << p1.use_count() << endl;
cout << p2.use_count() << endl;
// Relinquishes ownership of p1 on the object
//and pointer becomes NULL
p1.reset();
cout << p1.get() << endl;
cout << p2.use_count() << endl;
cout << p2.get() << endl;
return 0;
}
When to use shared_ptr?
Use shared_ptr if you want to share ownership of the resource . Many shared_ptr can point to a single resource. shared_ptr maintains a reference count for this propose. when all shared_ptr’s pointing to resource goes out of scope the resource is destroyed.
Use shared_ptr if you want to share ownership of the resource . Many shared_ptr can point to a single resource. shared_ptr maintains a reference count for this propose. when all shared_ptr’s pointing to resource goes out of scope the resource is destroyed.
Comments
Post a Comment