Say I have an object of type A having Initialize() method. The method receives object B, which are kept as the object data member. B object is shared between several objects, thus A should contain the originally received B object and not its copy.
class A
{
public:
bool Initialize(B?? b);
private:
B?? m_B;
}
Object B must present. Thus I think to pass it by reference, instead of passing by pointer and failing Initialize() in case B is NULL.
The only alrernative for m_B is to be of type of pointer B (it cann't be reference of B, since the intializating of B is not done in A c-tor). Thus Initialize should look like:
bool A::Initialize(B& b)
{
m_B = &b;
....
}
Is this aproach is ok?
UPD:
The code is not new and I'm just trying to "fix" some problems. Actually I'm not talking about some concrete A and b classes, rather about a way the problem is approached in my code base. The code widely passes pointer to B and verifying it in Initialize() if it's NULL.
Passing B to A's c-tor is not always a good option too. There're also other parametrs passed to A, which are not exists at A creation time. Therefore I woudln't prefer to pass part of parameters to A c-tor and the rest to A::Initialize().
shared_ptr can be "NULL" too, so passing it to A::Initialize() not different from passing just pointer to B, in that aspect that signature of Initialize() dosn't declare if B is mandatory or not. In my case it is and I want to express it by passing reference to B.
Our code currently is not using boost at all. So, although shared_ptr better solution than just passing raw pointer, can solution proposed by me be considered as bad, but still solution.