我正在研究一个处理框架,在这个框架中,回调被注册到事件中,并且为了确保在被删除的对象上不调用回调,我想使用弱捕获而不是引用捕获。使用C++14和shared_from_this()来完成这项工作并不是问题,但是如何使用C++17和weak_from_this()正确地实现这一点。
下面的示例在使用C++17时不输出任何内容。我使用的是g++ 6.3.0-18
#define CXX17 // When this is defined, nothing is printed
#ifdef CXX17
# include <experimental/memory>
# include
我有:
class A : public std::enable_shared_from_this<A>
{...};
class B : public A
{...};
void doCoolStuff(std::weak_ptr<A> obj)
{...}
void doCoolStuff(std::weak_ptr<B> obj)
{
...
doCoolStuff(std::static_pointer_cast<A>(obj.lock())); (1)
}
然后在B函数中:
void B::doReallyCoolStuff
据我所知,make_shared<T>(...)可以提供一些内存分配优化(它可以在与类T的实例相同的内存块中分配引用计数器)。
enable_shared_from_this是否提供了相同的优化?所以:
class T : std::enable_shared_from_this<T> {};
...
auto t = std::shared_ptr<T>(new T);
与以下相同:
class T {};
...
auto t = std::make_shared<T>();
如果没有考虑到规模(T)。
我有一个实现接口(Geometry)的类(LinkList)。我的示例底部的代码显然是错误的,所以我正在考虑实现std::enable_shared_from_this。Geometry能否安全地继承std::enable_shared_from_this<LinkList>,我能否安全地将getLinkList()方法更改为shared_from_this()?如果我的Geometry类有它继承的多个接口,我可以对所有接口这样做吗?
class Link
{
public:
std::string getName() { return "the name"
在第91页,我读过关于shared_from_this()的这篇文章
问题在于,shared_ptr将自己存储在Person基类的一个私有成员中,enable_shared_from_this<>,在人的结构的末尾中。
书中的相关代码片段是:
class Person : public std::enable_shared_from_this<Person> {
...
};
我不明白这里有两件事:
这个存储自己的shared_ptr是谁?
在Person的建设结束时,他怎么能在任何地方存储自己呢?我认为Person的构造以它的构造函数的最后一条语
我做了这个小功能,用于对任何有operator<的类型进行加权。我遵循了make_unique和make_shared与make_one的惯例。不知道这是不是最好的名字。
// Create a single instance of an object, using
// operator< to determine equality.
// Note that we take a value instead of a constructor
// arguments because often we'll want to mutate a field,
// then c
我收到以下错误:
class Test
{
std::map<std::string,Test> test;
};
错误是"Field有不完整的类型'Test'“。我读了一些帖子,暗示这可能是xcode附带的libcxx版本中的一个bug,但如果我只需将其更改为:
class Test
{
std::map<std::string,std::shared_ptr<Test>> test;
};
我只是想仔细检查一下,这绝对是一个正确的错误,而不是一个bug。
干杯!
所以我有一些代码:
class Thing
{
public:
Thing() = default;
};
class DbOfThings
{
public:
DbOfThings() = default;
std::weak_ptr<Thing> GetEntry(int someKey) const
{
// returns a weak_ptr from mThings, or null if a Thing
// that has someKey was not found
return