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
1