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;
}

Recommended Answers

All 3 Replies

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.

Thanks for your answer. i have changed implementation ,

b ( const b &obj):p(obj.p){}

write a c++ program on AUTOMATIC SEATING ARRANGEMENT FOR EXAMINATION

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.