Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Why we use shared_ptr?
XML
#include<iostream>
#include<memory>
#include <vector>

using namespace std;
class x
{
    public:
    int i;
    x():i(12323123)
    {
        cout<<"constructor called"<<endl;
    }
    ~x()
    {
        cout<<"destructor called"<<endl;
    }
};
    vector< shared_ptr<x> > testvec;

int test()
{
        shared_ptr<x> n(new x);
            testvec.push_back((n));
}

main()

{
    test();
    vector< shared_ptr<x> > tests=((testvec));
    cout<<(*(tests.at(0))).i;
}
Posted
Updated 18-Oct-12 0:54am
v2

It is used to remove the risk of memory leakage in an application, because you don't need to remember to manually delete the pointer when you a re done with it.
 
Share this answer
 
Comments
ppvijeesh1 18-Oct-12 7:19am    
Maximilien
Sorry. I think my question is not clear. Why we use shared_ptr instead of unique_ptr,etc?
Maximilien 18-Oct-12 7:30am    
Edit the original question ...

the best answer I can give you is to read this :
http://herbsutter.com/2012/01/20/gotw-103-smart-pointers-part-1-difficulty-310/
I assume shared_ptr is used rather than unique_ptr to be able to have copies of objects from that vector and still have correct reference count for each object.

so for code:
C++
shared_ptr<x> variable = new x;
{
    vector< shared_ptr<x> > arr;
    arr.push_back(x)
}
</x></x>


in the brackets variable will have ref count equal to 2, and equal to 1 otherwise.
 
Share this answer
 
Comments
ppvijeesh1 19-Oct-12 2:15am    
Thank u all for ur help n supprt.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900