c++ const shared_ptr
Explanation of using const
with shared_ptr
in C++
#include <iostream>
#include <memory>
int main() {
const std::shared_ptr<int> p1 = std::make_shared<int>(42);
// p1 = std::make_shared<int>(100); // Error: p1 is const, cannot be reassigned
*p1 = 100; // OK: the value pointed to by p1 can be modified
return 0;
}
- Include Necessary Headers:
Include the necessary headers for using
shared_ptr
and other standard library components.Create a Constant
shared_ptr
:Declare a constant
shared_ptr
namedp1
pointing to an integer with the value 42.Error on Reassignment:
Attempting to reassign
p1
to point to a different integer usingstd::make_shared<int>(100)
results in a compilation error becausep1
is constant.Modifying Pointed Value:
- Modifying the value pointed to by
p1
using the dereference operator*p1 = 100
is allowed, as the constantshared_ptr
only prevents reassignment of the pointer itself, not the value it points to.