- VisualStudio2022插件的安装及使用-编程手把手系列文章
- pprof-在现网场景怎么用
- C#实现的下拉多选框,下拉多选树,多级节点
- 【学习笔记】基础数据结构:猫树
std::enable_shared_from_this<T>
的类能够在其自身实例中通过 std::shared_from_this
方法创建一个指向自己的 std::shared_ptr<T>
智能指针。std::shared_ptr<T>
实例会造成严重的后果,其行为是未定义的。std::enable_shared_from_this<T>
实际包含了一个用于指向对象自身的 std::weak_ptr<T>
指针。本文介绍 std::enable_shared_from_this 及 std::shared_from_this 的基本概念和使用方法.
以下内容是 cppreference.com 上关于 std::enable_shared_from_this 的定义和说明:
Defined in header < memory > template< class T > class enable_shared_from_this; (since C++11) 。
std::enable_shared_from_this allows an object t that is currently managed by a std::shared_ptr named pt to safely generate additional std::shared_ptr instances pt1, pt2, ... that all share ownership of t with pt. 。
Publicly inheriting from std::enable_shared_from_this<T> provides the type T with a member function shared_from_this. If an object t of type T is managed by a std::shared_ptr<T> named pt, then calling T::shared_from_this will return a new std::shared_ptr<T> that shares ownership of t with pt. 。
简单来说就是,继承自 std::enable_shared_from_this<T> 的类能够在其自身实例中通过 std::shared_from_this 方法创建一个指向自己的 std::shared_ptr<T> 智能指针.
想要理解 std::enable_shared_from_this<T>,首先得知道为什么需要 std::enable_shared_from_this<T>,请看下文.
为什么需要 std::enable_shared_from_this<T>? 我们从一个例子讲起,会更容易一些.
假定有一个类 Processor, 它的作用是异步处理数据并且存储到数据库。当 Processor 接收到数据时,它通过一个定制的 Executor 类型来异步处理数据:
class Executor {
public:
//Executes a task asynchronously
void
execute(const std::function<void(void)>& task);
//....
private:
/* Contains threads and a task queue */
};
class Processor {
public:
//...
//Processes data asynchronously. (implemented later)
void processData(const std::string& data);
private:
//Called in an Executor thread
void doProcessAndSave(const std::string& data) {
//1. Process data
//2. Save data to DB
}
//.. more fields including a DB handle..
Executor* executor;
};
Client 类包含了一个 std::shared_ptr<Processor> 实例,Processor 从 Client 类接收数据:
class Client {
public:
void someMethod() {
//...
processor->processData("Some Data");
//..do something else
}
private:
std::shared_ptr<Processor> processor;
};
以上示例中,Executor 是一个线程池,用于执行任务队列中的任务。 在 Processor::processData 中,我们需要传递一个(指针)函数(lambda 函数)给 Executor 来执行异步操作。该 lambda 函数调用 Processor::doProcessAndSave 以完成实际的数据处理工作。因此,该 lambda 函数需要捕获一个 Processor 对象的引用/指针。我们可以这样做:
void Processor::processData(const std::string& data) {
executor->execute([this, data]() { //<--Bad Idea
//Executes in an Executor thread asynchronously
//'this' could be invalid here.
doProcessAndSave(data);
});
}
然而,因为种种原因,Client 可能会随时重置 std::shared_ptr<Processor>,这可能导致 Processor 的实例被析构。因此,在执行 execute 函数时或者在执行之前,上述代码中捕获的 this 指针随时可能会变为无效指针.
怎么办?
我们可以通过在 lambda 函数中捕获并保留一个指向当前对象本身的 std::shared_ptr<Processor> 实例来防止 Processor 对象被析构.
下图展示了示例代码的交互逻辑:
那么,在 Processor 实例中通过 shared_ptr (this) 创建一个智能指针呢?其行为是未定义的! 。
std::shared_ptr<T> 允许我们安全地访问和管理对象的生命周期。多个 std::shared_ptr<T> 实例通过一个共享控制块结构(a shared control block structure)来管理对象的生命周期。一个控制块维护了一个引用计数,及其他必要的对象本身的信息.
void good() {
auto p{new int(10)}; //p is int*
std::shared_ptr<int> sp1{p};
//Create additional shared_ptr from an existing shared_ptr
auto sp2{sp1}; //OK. sp2 shares control block with sp1
}
从一个裸指针创建一个 std::shared_ptr<T> 会创建一个新的控制块。从一个裸指针创建多个 std::shared_ptr<T> 实例会造成严重的后果:
void bad() {
auto p{new int(10)};
std::shared_ptr<int> sp1{p};
std::shared_ptr<int> sp2{p}; //! Undefined Behavior
}
因此,我们需要一个机制能够达到我们的目的(捕获并保留一个指向当前对象本身的 std::shared_ptr<Processor> 实例).
这就是 std::enable_shared_from_this<T> 存在的意义,以下是修改后的类 Processor 实现
class Processor : public std::enable_shared_from_this<Processor> {
//..same as above...
};
void Processor::processData(const std::string& data) {
//shared_from_this() returns a shared_ptr<Processor>
// to this Processor
executor->execute([self = shared_from_this(), data]() {
//Executes in an Executor thread asynchronously
//'self' is captured shared_ptr<Processor>
self->doProcessAndSave(data); //OK.
});
}
self = shared_from_this() 传递的是一个合法的 std::shared_ptr<Processor> 实例,合法的类 Processor 对象的引用.
std::enable_shared_from_this<T> 的实现类似:
template<class T>
class enable_shared_from_this {
mutable weak_ptr<T> weak_this;
public:
shared_ptr<T> shared_from_this() {
return shared_ptr<T>(weak_this);
}
//const overload
shared_ptr<const T> shared_from_this() const {
return shared_ptr<const T>(weak_this);
}
//..more methods and constructors..
//there is weak_from_this() also since C++17
template <class U> friend class shared_ptr;
};
enable_shared_from_this 包含了一个 std::weak_ptr<T> 指针,这正是函数 shared_from_this 返回的内容。注意,为什么不是 std::shared_ptr<T>? 因为对象包含自身的计数引用会导致对象永远不被释放,从而发生内存泄漏。上述代码中 weak_this 会在类对象被 std::shared_ptr<T> 引用时赋值,也就是std::shared_ptr<T> 实例的构造函数中赋值,这也是为什么类 enable_shared_from_this 的最后,其被声明成为了 shared_ptr 的友元.
到此,关于 std::enable_shared_from_this<T> 的介绍就结束了.
https://en.cppreference.com/w/cpp/memory/enable_shared_from_this https://www.nextptr.com/tutorial/ta1414193955/enable_shared_from_this-overview-examples-and-internals 。
最后此篇关于何时/如何使用std::enable_shared_from_this?的文章就讲到这里了,如果你想了解更多关于何时/如何使用std::enable_shared_from_this?的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我对这个错误很困惑: Cannot implicitly convert type 'System.Func [c:\Program Files (x86)\Reference Assemblies\
考虑这段代码: pub trait Hello { fn hello(&self); } impl Hello for Any { fn hello(&self) {
问题很简单。是否可以构造这样一个类型 T,对于它下面的两个变量声明会产生不同的结果? T t1 = {}; T t2{}; 我已经研究 cppreference 和标准一个多小时了,我了解以下内容:
Intellij idea 给我这个错误:“Compare (T, T) in Comparator cannot be applied to (T, T)” 对于以下代码: public class
任何人都可以告诉我 : n\t\t\t\t\n\t\t\t 在以下来自和 dwr 服务的响应中的含义和用途是什么. \r\n\t\t\t \r\n\t\t\t
让 T 成为一个 C++ 类。 下面三个指令在行为上有什么区别吗? T a; T a(); T a = T(); T 为不带参数的构造函数提供了显式定义这一事实是否对问题有任何改变? 后续问题:如果
Rust中的智能指针是什么 智能指针(smart pointers)是一类数据结构,是拥有数据所有权和额外功能的指针。是指针的进一步发展 指针(pointer)是一个包含内存地
比如我有一个 vector vector > v={{true,1},{true,2},{false,3},{false,4},{false,5},{true,6},{false,7},{true,8
我有一个来自 .xls 电子表格的数据框,我打印了 print(df.columns.values) 列,输出包含一个名为:Poll Responses\n\t\t\t\t\t。 我查看了 Excel
This question already has answers here: What are good reasons for choosing invariance in an API like
指针类型作为类型前缀与在类型前加斜杠作为后缀有什么区别。斜线到底是什么意思? 最佳答案 语法 T/~ 和 T/& 基本上已被弃用(我什至不确定编译器是否仍然接受它)。在向新向量方案过渡的初始阶段,[T
我正在尝试找到一种方法来获取模板参数的基类。 考虑以下类: template class Foo { public: Foo(){}; ~Foo(){};
这是一个让我感到困惑的小问题。我不知道如何描述它,所以只看下面的代码: struct B { B() {} B(B&) { std::cout ::value #include
为什么有 T::T(T&) 而 T::T(const T&) 更适合 copy ? (大概是用来实现move语义的???) 原始描述(被melpomene证明是错误的): 在C++11中,支持了一种新
在 Java 7 中使用 eclipse 4.2 并尝试实现 List 接口(interface)的以下方法时,我收到了警告。 public T[] toArray(T[] a) { ret
假设有三个函数: def foo[T](a:T, b:T): T = a def test1 = foo(1, "2") def test2 = foo(List(), ListBuffer()) 虽
我对柯里化(Currying)和非柯里化(Currying)泛型函数之间类型检查的差异有点困惑: scala> def x[T](a: T, b: T) = (a == b) x: [T](a: T,
考虑一个类A,我如何编写一个具有与相同行为的模板 A& pretty(A& x) { /* make x pretty */ return x; } A pretty(A&& x) {
Eclipse 表示由于泛型类型橡皮擦,类型参数不允许使用 instanceof 操作。 我同意在运行时不会保留任何类型信息。但是请考虑以下类的通用声明: class SomeClass{ T
在 C++14 中: 对于任何整数或枚举类型 T 以及对于任何表达式 expr: 有没有区别: struct S { T t { expr }; }; 和 struct S { T t = { exp
我是一名优秀的程序员,十分优秀!