Skip to content

Update smart-pointers.md: transfer of ownership #6694

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions content/cpp/concepts/smart-pointers/smart-pointers.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,28 @@ Both `unique_ptr` and `shared_ptr` have a corresponding function to create their
- `std::make_unique<T>(value)` for `unique_ptr`
- `std::make_shared<T>(value)` for `shared_ptr`

### Transfer of Ownership Limitations

It must be noted that the ownership of can be transferred from a unique pointer to shared pointer but not vice-versa. As the shared pointer is designed to "share" the resource by updating the reference count. This underlying principle gets violated when an attempt is made to completely transfer ownership out of it.

```cpp
#include <memory>

int main() {
std::unique_ptr<int> ptrU1 = std::make_unique<int>(50);
std::unique_ptr<int> ptrU2 = std::make_unique<int>(20);
std::shared_ptr<int> ptrS1 = std::make_shared<int>(10);

ptrS1 = std::move(ptrU1); //allowed, compiles.
std::shared_ptr<int> ptrS2 = std::move(ptrU2); //allowed, compiles.

std::unique_ptr<int> ptrU3 = std::move(ptrS2); //not allowed, doesn't compile.
ptrU1 = std::move(ptrS1); //not allowed, doesn't compile.

}

```

## Unique Pointers

```cpp
Expand Down