In this article we will compare C++11 Smart Pointer Implementation shared_ptr and a normal pointer.
Let’s compare shared_ptr and raw pointer based on following aspects i.e.
Missing ++, – – and [] operator
In comparison to a raw pointer, shared_ptr provides only these operators
1.) -> , *
2.) Â Comparison Operators
Frequently Asked:
But shared_ptr doesn’t provide,
1.) Â Pointer arithmetic like +, -, ++, —
2.) Â Operator []
Checkout below example,
#include<iostream> #include<memory> struct Sample { void dummyFunction() { std::cout << "dummyFunction" << std::endl; } }; int main() { std::shared_ptr<Sample> ptr = std::make_shared<Sample>(); (*ptr).dummyFunction(); // Will Work ptr->dummyFunction(); // Will Work // ptr[0]->dummyFunction(); // This line will not compile. // ptr++; // This line will not compile. //ptr--; // This line will not compile. std::shared_ptr<Sample> ptr2(ptr); if (ptr == ptr2) // Will work std::cout << "ptr and ptr2 are equal" << std::endl; return 0; }
Output:
Best Resources to Learn C++:
dummyFunction dummyFunction ptr and ptr2 are equal
 NULL Check
When we create shared_ptr object without assigning any value then its empty.
Where as, without declaration raw pointer will contain garbage value and we cannot verify if it contains garbage or not 🙂
With shared_ptr user can check for emptiness like this,
std::shared_ptr<Sample> ptr3; if(!ptr3) std::cout<<"Yes, ptr3 is empty" << std::endl; if(ptr3 == NULL) std::cout<<"ptr3 is empty" << std::endl; if(ptr3 == nullptr) std::cout<<"ptr3 is empty" << std::endl;
We can also access the internal raw pointer from shared_ptr object like this,
std::shared_ptr<Sample> ptr = std::make_shared<Sample>(); Sample * rawptr = ptr.get();
Ideally we should not use this because it can cause problem if we delete this pointer by mistake. In that case when shared_ptr object will go out of scope then it will try to delete already deleted memory and it will create our program to crash. We will discuss this in more detail in next post.