I am trying to swap a pointer to point to the address of a new class instance created inside a method, but once back to main, the reference is lost, is this because of scope? Could someone please care to explain? Does c/c++ have reference counting?
#include <iostream>
class MyClass {
public:
int myNum;
std::string myString;
MyClass(int my_num, std::string my_string)
{
myNum = my_num;
myString = my_string;
}
};
void SwapRef(MyClass **p)
{
MyClass b(99, "test");
*p = &b;
}
int main(int argc, char* argv[])
{
MyClass a(1, "main");
MyClass* aPtr = (MyClass*)0;
aPtr = &a;
std::cout << "myNum is: " << aPtr->myNum << " myString is: " << aPtr->myString << "\n";
SwapRef(&aPtr);
std::cout << "myNum is: " << aPtr->myNum << " myString is: " << aPtr->myString << "\n";
#ifdef _WIN32 || _WIN64
system("pause");
#endif
}
OUTPUT:
myNum is: 1 myString is: main
myNum is: -858993460 myString is:
This function
void SwapRef(MyClass **p)
{
MyClass b(99, "test");
*p = &b;
}
is wrong. The object b
having automatic storage duration will not be alive after exiting the function. So the pointer aPtr
assigned in the function with the address of the local object using the expression statement
*p = &b;
will be invalid after exiting the function.
Dereferencing such a pointer invokes undefined behavior.
Instead you could write
**p = b;
using the generated by the compiler the default copy assignment operator.
The function could be correct if the object declared within the function would have static storage duration like
void SwapRef(MyClass **p)
{
static MyClass b(99, "test");
*p = &b;
}
In this case it will be alive after exiting the function.
Pay attention to that you should include header <string>
#include <string>
because it is not necessary that the header <iostream>
includes the header <string>
.