[英]How to make a list of share_ptr?
I am facing a design issue that could be summarized by the following class: A linked list of shared buffer where the linking element is a SharedBuffer 我面临的设计问题可以由以下类总结:共享缓冲区的链接列表,其中链接元素是SharedBuffer
class SharedBuffer : public shared_ptr<Buffer> {
private:
SharedBuffer _next;
SharedBuffer(Buffer* buffer) : shared_ptr<Buffer>(buffer) {}
~SharedBuffer() {
if (_next)
_next.reset();
}
};
This class is wrong because it references itself in its own definition. 此类是错误的,因为它在自己的定义中引用了自己。 But that the idea. 但是那个主意。 Any idea on making such a list of shared buffer? 关于建立共享缓冲区列表的任何想法吗?
The short answer is 简短的答案是
There are many container classes in the stl. stl中有许多容器类。 std::vector<>
, std::list<>
or whatever other container you are looking for. std::vector<>
, std::list<>
或您要查找的任何其他容器。 Do not roll your own. 不要自己动手。 Please. 请。 You will only make mistakes and your time could be better spent working on your program logic instead of debugging a bad implementation of something, especially when good implementations are available for free. 您只会犯错,并且可以花更多的时间在程序逻辑上,而不是调试某些错误的实现,尤其是当好的实现是免费提供的时候。
std::vector<std::shared_ptr<Buffer>> sharedBuffers;
If your SharedBuffer
really should stay a Shared object, just like shared_ptr
is a shared "object" (object being pointer here, and sharing means shared ownership), but you want to have it reference-counted, you could simply hold a shared_ptr
inside it rather than inheriting (which is a bad idea, especially considering the problems leading up to make_shared
). 如果您的SharedBuffer
确实应该保留一个Shared对象,就像shared_ptr
是一个共享的“对象”(对象在这里是指针,并且共享意味着共享所有权)一样,但是您想对其进行引用计数,则只需在其中包含一个shared_ptr
而不是继承(这是一个坏主意,尤其是考虑到导致make_shared
的问题)。
class SharedBuffer {
private:
std::shared_ptr<Buffer> _buffer;
SharedBuffer _next;
SharedBuffer(Buffer* buffer) : _buffer{buffer} {}
// note the following is now redundant, since it happens automatically
/*~SharedBuffer() {
if (_next)
_next.reset();
}*/
/* Other protected operations (e.g. read/write) */
};
Even better, you should already accept a shared_ptr
in SharedBuffer
's constructor. 更好的是,您应该已经在SharedBuffer
的构造函数中接受了shared_ptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.