std::unique_ptr::swap

void swap(unique_ptr& other) noexcept;
(C++11 起)

交换 *this 和另一 unique_ptr 对象 other 的被管理对象和关联的删除器。

参数

other - 要与之交换被管理对象和删除器的另一 unique_ptr 对象

返回值

(无)

示例

#include <iostream>
#include <memory>
 
struct Foo {
    Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n"; }
    int val;
};
 
int main()
{
    std::unique_ptr<Foo> up1(new Foo(1));
    std::unique_ptr<Foo> up2(new Foo(2));
 
    up1.swap(up2);
 
    std::cout << "up1->val:" << up1->val << std::endl;
    std::cout << "up2->val:" << up2->val << std::endl;
}

输出:

Foo...
Foo...
up1->val:2
up2->val:1
~Foo...
~Foo...

版本历史

  • (当前 | 先前 2017年9月11日 (一) 04:58Fruderica讨论 | 贡献. . (947字节) (-450). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:58P12bot讨论 | 贡献 . . (1,397字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:08P12bot讨论 | 贡献 . . (1,397字节) (-26). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 14:02P12bot讨论 | 贡献 . . (1,423字节) (+273). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:45P12讨论 | 贡献 . . (1,150字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,150字节) (-42). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:56P12讨论 | 贡献 . . (1,192字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,192字节) (+1,192). . (Translated from the English version using Google Translate)