I know that unique_ptr
makes the smart pointer own the resource and thus it doesn't allow multiple pointers to point to the same resource.
But why then is it allowed to create a raw pointer of that smart pointer with .get()
and then pass it to a function?
At the end you have two pointers that have ownership of the resource and with the ability to change its value? Which would violate the rule of unique_ptr smart ptr exclusively owning the resource.
In the example below I made a simple program that changes the value that the smrt pointer smrtPtr
is pointing at.
Ex:
#include <iostream>
#include <memory>
#include <utility> //move semantics
void changeValue(int* ptr)
{
if (!ptr) //check if pointer is null
return;
*ptr = 17; //change value to 17
}
int main()
{
auto smrtPtr{ std::make_unique<int>(5) };
changeValue(smrtPtr.get()); //creates a raw pointer of smrtPtr
if (smrtPtr) //if it does contain resource
std::cout << *smrtPtr;
return 0;
}
Thanks a lot
Your entire question is based on confusion of what a smart pointer does:
"and thus it doesn't allow multiple pointers to point to the same resource."
It does no such thing. A smart pointer determines who OWNS the resource, not who can view the resource.
The responsibility of the owner is to delete the resource at the correct time. This means not deleting it before other things are done reading it.
A unique pointer means it is the only thing responsible for deletion. A shared pointer means that the last shared pointer around is responsible for deletion.
None of this impacts the ability to access the resource.