Nik*_*kko 14 c++ embedded boost smart-pointers
我在嵌入式Linux环境中使用C++ GCC version 2.95.
我只是无法boost::shared_ptr用bcp 提取文件,它太重了.
我想要的是一个简单的智能指针实现,boost::shared_ptr但没有所有boost开销(如果可能......).
我可以拿出我自己的版本的阅读升压源,但我生怕漏掉一个或多个点,似乎容易使出现故障的智能指针,我不能忍受任何会马车实现.
那么,是否存在一个"简单"的实现或实现示例boost::shared_ptr(或任何引用计数等效智能指针)我可以使用或者我可以作为灵感?
Emi*_*lia 10
如果你不需要混合共享和弱 ptr,并且不需要coustom deletors,你可以使用快速和脏的my_shared_ptr:
template<class T>
class my_shared_ptr
{
template<class U>
friend class my_shared_ptr;
public:
my_shared_ptr() :p(), c() {}
explicit my_shared_ptr(T* s) :p(s), c(new unsigned(1)) {}
my_shared_ptr(const my_shared_ptr& s) :p(s.p), c(s.c) { if(c) ++*c; }
my_shared_ptr& operator=(const my_shared_ptr& s)
{ if(this!=&s) { clear(); p=s.p; c=s.c; if(c) ++*c; } return *this; }
template<class U>
my_shared_ptr(const my_shared_ptr<U>& s) :p(s.p), c(s.c) { if(c) ++*c; }
~my_shared_ptr() { clear(); }
void clear()
{
if(c)
{
if(*c==1) delete p;
if(!--*c) delete c;
}
c=0; p=0;
}
T* get() const { return (c)? p: 0; }
T* operator->() const { return get(); }
T& operator*() const { return *get(); }
private:
T* p;
unsigned* c;
}
Run Code Online (Sandbox Code Playgroud)
对于任何有兴趣的人来说make_my_shared<X>,它可以简单地实现为
template<class T, class... U>
auto make_my_shared(U&&... u)
{
return my_shared_ptr<T>(new T{std::forward<U>(u)...});
}
Run Code Online (Sandbox Code Playgroud)
被称为
auto pt = make_my_shared<T>( ... );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3317 次 |
| 最近记录: |