Reputation:
I have 2 classes, A and B.
In class A, I have a pointer on B called Bptr.
I allocate memory for Bptr in the constructor of A, and I free memory of Bptr in A's destructor.
class B {
//whatever
public:
B(int,int);
}
class A {
private:
B * Bptr;
public:
A();
}
A::A(){
Bptr = new B(2,5);
}
A::~A(){
delete Bptr;
}
How can I integrate Boost in my code and use the smart pointer : boost::shared_ptr ? How would my code look like?
Thanks a lot!
Upvotes: 0
Views: 91
Reputation: 254461
The first question to ask yourself: why do you want to dynamically allocate the object in the first place? Can you just replace the pointer with a member of type B
?
Assuming there is a good reason, then why shared_ptr
(rather than scoped_ptr
or, in modern C++, unique_ptr
)? Why do you need shared ownership?
Once you've answered these questions, and determined that shared ownership is the right solution, just replace B*
with a shared pointer, initialise it in the constructor, and get rid of the redundant destructor (assuming it's not needed for anything else).
class A {
private:
boost::shared_ptr<B> Bptr;
public:
A() : Bptr(boost::make_shared<B>(2,5)) {}
};
You could simply initialise it with a pointer, Bptr(new B(2,5))
, but using make_shared
makes more efficient use of memory and (in more complicated situations than this) makes it easier to ensure exception safety.
Upvotes: 1
Reputation: 8677
class B {
//whatever
public:
B(int,int);
}
class A {
private:
boost::shared_ptr<B> Bptr;
public:
A();
}
A::A(){
Bptr = boost::make_shared<B>(2,5);
}
A::~A(){
// Bptr automatically deleted if this is the only boost::shared_ptr pointing to it
}
Although you could simply use new B(2,5)
instead of boost::make_shared<B>
, the latter is exception-safe.
Upvotes: 0