Skip to content

Commit 68d5ca4

Browse files
author
Colin Robertson
committed
Restore accidentally deleted swap
1 parent 2e76ff1 commit 68d5ca4

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

docs/standard-library/shared-ptr-class.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,67 @@ use count == 2
690690
use count == 1
691691
```
692692

693+
## <a name="swap"></a> swap
694+
695+
Swaps two `shared_ptr` objects.
696+
697+
```cpp
698+
void swap(shared_ptr& sp) noexcept;
699+
```
700+
701+
### Parameters
702+
703+
*sp*\
704+
The shared pointer to swap with.
705+
706+
### Remarks
707+
708+
The member function leaves the resource originally owned by `*this` subsequently owned by *sp*, and the resource originally owned by *sp* subsequently owned by `*this`. The function does not change the reference counts for the two resources and it does not throw any exceptions.
709+
710+
### Example
711+
712+
```cpp
713+
// std__memory__shared_ptr_swap.cpp
714+
// compile with: /EHsc
715+
#include <memory>
716+
#include <iostream>
717+
718+
int main()
719+
{
720+
std::shared_ptr<int> sp1(new int(5));
721+
std::shared_ptr<int> sp2(new int(10));
722+
std::cout << "*sp1 == " << *sp1 << std::endl;
723+
724+
sp1.swap(sp2);
725+
std::cout << "*sp1 == " << *sp1 << std::endl;
726+
727+
swap(sp1, sp2);
728+
std::cout << "*sp1 == " << *sp1 << std::endl;
729+
std::cout << std::endl;
730+
731+
std::weak_ptr<int> wp1(sp1);
732+
std::weak_ptr<int> wp2(sp2);
733+
std::cout << "*wp1 == " << *wp1.lock() << std::endl;
734+
735+
wp1.swap(wp2);
736+
std::cout << "*wp1 == " << *wp1.lock() << std::endl;
737+
738+
swap(wp1, wp2);
739+
std::cout << "*wp1 == " << *wp1.lock() << std::endl;
740+
741+
return (0);
742+
}
743+
```
744+
745+
```Output
746+
*sp1 == 5
747+
*sp1 == 10
748+
*sp1 == 5
749+
*wp1 == 5
750+
*wp1 == 10
751+
*wp1 == 5
752+
```
753+
693754
## <a name="unique"></a> unique
694755

695756
Tests if owned resource is unique. This function was deprecated in C++17, and removed in C++20.

0 commit comments

Comments
 (0)