I'm trying to port over some code that uses pointers, to a different location with the different sections of the code in separate functions. However, I keep getting undefined behaviour from the pointers and was not able to understand why.
A sample of how my code is currently is as follows. I am using TAEF
In TestClass.h
class TestClass{
CurrentData* data1;
CurrentData* data2;
};
In TestClass.cpp
// initialize pointer
TestClass::MethodSetup()
{
data1 = new CurrentData();
data2 = new CurrentData();
}
// actual test function
TestClass::Test1()
{
SetupData();
Verify(data1);
Verify(data2);
}
// supplementary functions
TestClass::SetupData()
{
SetupStep(&data1);
SetupStep(&data2);
}
TestClass::SetupStep(CurrentData** p_Data)
{
CurrentDataRequest req;
csref<CurrentDataResponse> resp;
// send request and get response
*p_Data = (*resp)->m_Data;
}
TestClass::Verify(CurrentData* cd)
{
VERIFY_IS_EQUAL(cd->val, 0);
}
// cleanup
TestClass::MethodCleanup()
{
delete data1;
delete data2;
}
I have only made the wrappers SetupData()
and Verify()
, not the code inside them. SetupStep()
is auxiliary both here and in the original. In the original version of the code, the code blocks inside each wrapper would execute in the same scope with a single pointer CurrentData* cd
defined before testing begins. I expected that my code would behave identically to the original code and pass tests as expected, but I observed that the value of members of the cd pointer is pointing to change unexpectedly i.e. undefined behaviour.
Another problem is I want to keep the pointers as is as there are multiple data members to maintain and with unique pointers, it seems not recommended to pass them to functions as references, as seen in a highly upvoted comment to the first reply here