std::enable_shared_from_this::shared_from_this

shared_ptr<T> shared_from_this();
(1)
shared_ptr<T const> shared_from_this() const;
(2)

返回与所有指代 *thisstd::shared_ptr 共享 *this 所有权的 std::shared_ptr<T>

等效地执行 std::shared_ptr<T>(weak_this) ,其中 weak_thisenable_shared_from_this 的私有 mutable std::weak_ptr<T> 成员。

目录

注意

只容许在先前共享的对象,即 std::shared_ptr 所管理的对象上调用 shared_from_this 。否则行为未定义 (C++17 前)抛出 std::bad_weak_ptr (由 shared_ptr 从默认构造的 weak_this 的构造函数) (C++17 起)

返回值

与之前存在的 std::shared_ptr 共享 *this 所有权的 std::shared_ptr<T>

示例

#include <iostream>
#include <memory>
 
struct Foo : public std::enable_shared_from_this<Foo> {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; } 
    std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
 
int main() {
    Foo *f = new Foo;
    std::shared_ptr<Foo> pf1;
 
    {
        std::shared_ptr<Foo> pf2(f);
        pf1 = pf2->getFoo();  // 与 pf2 的对象共享所有权
    }
 
    std::cout << "pf2 is gone\n";   
}

输出:

Foo::Foo
pf2 is gone
Foo::~Foo

参阅

(C++11)
拥有共享对象所有权语义的智能指针
(类模板)

版本历史

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