Boost logo

Boost Users :

Subject: [Boost-users] Accessing members from a shared pointer passed as argument to a function gives incorrect results without typecast
From: Deepak Gunjal (dgunjal_at_[hidden])
Date: 2013-04-15 06:02:12


Hi,

class A;
class B;
typedef boost::shared_ptr<A> pSharedPtrA;
typedef boost::shared_ptr<B> pSharedPtrB;

class B {
public:
int memberB;
};

Class A {

public:

 pSharedPtrB pMember;

};

Suppose i have one shared pointer of type pSharedPtrA pointing to an object
of class A and the member variable pMember pinging to a valid object of
class B.

Now if i pass the shared pointer of type pSharedPtrA to a function suppose
Test_Func(pSharedPtrA):
void Test_Func(pSharedPtrA pLocalA)
{
 pSharedPtrA ptrA = boost::static_pointer_cast<A> (pLocalA)

 pSharedPtrB tmpB = boost::static_pointer_cast<B>(ptrA->pMember)

  Another_Func(tmpB)
}

Another_Func(pSharedPtrB pLocalB)
{
   int x = pLocalB->memberB; //Gives WRONG value
  pSharedPtrB ptmp = boost::static_pointer_cast<B> (pLocalB)

  x = ptmp ->memberB; //Gives CORRECT Value

}

The problem is when typecast is not used then in function
Another_Func(pSharedPtrB pLocalB), pLocalB->memberB is not giving the
correct result but after typecast it is giving the correct results.

The inference is that in function Another_Func() data is preserved in the
pLocalB but without typecast i am not able to access it.

Though i have not declared any virtual functions in above code but where we
are having problem does contain the vritual functions. I dont know if it
has any bearing on behavior observed.

I want to know why typecasting is required to get the correct result and
why cant i access the members without typecasting.

Thanks and Regards
Deepak



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net