The get()
method of smart pointers like std::unique_ptr
and std::shared_ptr
returns a raw pointer to the managed object. While this can be useful, it can also lead to some pitfalls.
When you use get()
to retrieve a raw pointer from a smart pointer, you might inadvertently start managing the memory manually. This can defeat the purpose of using a smart pointer. For example:
void DangerousFunction() {
std::unique_ptr<int> p{
std::make_unique<int>(42)};
int* rawPtr = p.get();
// Manual deletion - Bad practice
delete rawPtr;
}
In this code, manually deleting rawPtr
is incorrect because p
still owns the memory, and deleting it results in undefined behavior.
If you store the raw pointer obtained from get()
and use it later, it can lead to use-after-free errors. For example:
void UseAfterFree() {
std::shared_ptr<int> p{
std::make_shared<int>(42)};
int* rawPtr = p.get();
// p goes out of scope and the memory is freed
std::cout << *rawPtr;
}
Accessing rawPtr
after p
is destroyed will result in undefined behavior because the memory has been deallocated.
get()
, use the smart pointer methods directly when possible. For example, use p
or p->
instead of p.get()
to access the value.get()
, always check if the returned raw pointer is not null before dereferencing it.void SafeFunction() {
std::unique_ptr<int> p{
std::make_unique<int>(42)};
int* rawPtr = p.get();
if (rawPtr) {
std::cout << *rawPtr;
}
}
In this way, you can avoid the common pitfalls and leverage smart pointers effectively.
Answers to questions are automatically generated and may not have been reviewed.
Learn the techniques and pitfalls of manual memory management in C++