Post date: Jul 21, 2017 2:26:35 AM
Shared and Unique Pointers are the STL library's implementation of smart pointers i.e. pointers that facilitates the management of memory allocated for the pointer used. This can reduce a lot of work in C++ programs. So after seemingly encountering an app that apparently works well with an undeleted new, I tried smart pointers. I append some code that shows how the pointers work.
void printNormalPointer(std::string* pstr)
{
std::cout << "NormalPointer: " << *pstr << "\n";
}
void printSharedPointer(std::shared_ptr<std::string> spstr)
{
std::cout << "SharedPointer: " << *spstr << "\n";
}
int main(int argc, char* argv[])
{
std::string* A = new std::string("Hello");
std::shared_ptr<std::string> spA(A);
std::cout << "address of ptr:" << &A << " pointing at " << A << " which holds " << *A <<"\n";
std::cout << "address of sptr:" << &spA << " pointing at " << spA.get() << " which holds " << *spA << "\n";
printNormalPointer(A);
printSharedPointer(spA);
std::shared_ptr<std::string> spB = std::make_shared<std::string>("World");
std::cout << "address of sptr:" << &spB << " pointing at " << spB << " which holds " << *spB << "\n";
std::getchar();
}
One point. These smart pointers do not work translating object reference addresses e.g.
void Test(class * classPtr)
{
....
}
....
class K;
Test(&K);
What happens is that on exiting the program, the program crashes. The work around is to use dynamic memory allocation through the smart pointers.