A quick question regarding the usage of a shared pointer in c++, and my apologies if this question is rather dimwitted:
Would an approach like this be considered poor design, or is this what shared_ptr's are for:
Let's say I have a class A and B
class A
{
public:
int firstInteger = 0;
};
class B
{
public:
void functionThatUsesA(A &refToInstanceA); //have to pass in reference to A every iteration
}; Rather than pass A into the function of B every iteration, could I just create a shared_ptr set to a shared_ptr of instance A?
class A
{
public:
int firstInteger = 0;
};
class B
{
public:
void setPointerToA(std::shared_ptr &refToA);
void functionThatUsesA();
private:
std::shared_ptr pointerToA;
};
void B::setPointerToA(std::shared_ptr &refToA)
{
pointerToA = refToA;
}
void B::functionThatUsesA() //no longer needs the reference to class A passed in
{
pointerToA.firstInteger +=1;
}
This does work, and the benefit (as I am seeing it), is that I don't have to pass in a reference to the first class every iteration, as the second class has a shared_ptr to work with.
However, I worry there are some design pitfalls I'm overlooking here, or performance issues I'm not seeing, or simply something I'm unaware of (I would guess it's actually easier on the cpu as it's not copying anything for the parameter, but I haven't profiled it, and I could be mistaken). I can imagine this getting rather convoluted, if not used sparingly (I imagine if the shared_ptr count got rather high, it could be difficult to debug where exactly you're doing something to the object it references).
Anyhow, my question is whether this is a terrible idea, for reasons I'm overlooking, or if this would be considered a rather typical use of shared_ptrs and is completely recommended? I find plenty of information out there of how shared_ptrs work but little in the way of practical use cases for them. I'd welcome any advice, whether general or specific here. Thanks in advance :)