0

Hi All,

I just want to know whether use of shared_ptr is justified in below code here or do i need to use unique_ptr instead of shared_ptr?

#include <iostream>
#include <memory>
using namespace std;

class a
{
int a1 ,b;
public:
a(int x=0,int y=0):a1(x),b(y){}
void fun1() {cout<<a1;cout<<b;}
};

class b
{
private:
std::shared_ptr <a> p;
public:
b (int x=0, int y=0):p( new  a (x,y)){}
b ( const b &obj):p(new a(*obj.p)){}
void fun2(){p->fun1();}
};


int main()
{
b obj1(10,20);
b obj2(obj1);
obj2.fun2();
return 1;
}
3
Contributors
3
Replies
10
Views
1 Year
Discussion Span
Last Post by madhav sai
1

Using a shared pointer to an a in class b means in b's copy constructor you don't need to create a new instance of a. You can simply assign the copied object's p member to the new object's. That's the whole point of shared pointers - that you can have multiple references to the object they point to, and until all references go away, the object will not be deleted.

0

Thanks for your answer. i have changed implementation ,

b ( const b &obj):p(obj.p){}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.