c_cpp count_ptr / shared_ptr
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp count_ptr / shared_ptr相关的知识,希望对你有一定的参考价值。
/*
The following code example is taken from the book
The C++ Standard Library - A Tutorial and Reference
by Nicolai M. Josuttis, Addison-Wesley, 1999
© Copyright Nicolai M. Josuttis 1999
*/
#ifndef COUNTED_PTR_HPP
#define COUNTED_PTR_HPP
/* class for counted reference semantics
* - deletes the object to which it refers when the last CountedPtr
* that refers to it is destroyed
*/
template <class T>
class CountedPtr {
private:
T* ptr; // pointer to the value
long* count; // shared number of owners
public:
// initialize pointer with existing pointer
// - requires that the pointer p is a return value of new
explicit CountedPtr (T* p=0)
: ptr(p), count(new long(1)) {
}
// copy pointer (one more owner)
CountedPtr (const CountedPtr<T>& p) throw()
: ptr(p.ptr), count(p.count) {
++*count;
}
// destructor (delete value if this was the last owner)
~CountedPtr () throw() {
dispose();
}
// assignment (unshare old and share new value)
CountedPtr<T>& operator= (const CountedPtr<T>& p) throw() {
if (this != &p) {
dispose();
ptr = p.ptr;
count = p.count;
++*count;
}
return *this;
}
// access the value to which the pointer refers
T& operator*() const throw() {
return *ptr;
}
T* operator->() const throw() {
return ptr;
}
private:
void dispose() {
if (--*count == 0) {
delete count;
delete ptr;
}
}
};
#endif /*COUNTED_PTR_HPP*/
以上是关于c_cpp count_ptr / shared_ptr的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp _strlwr&_strupr
llvm中内在的cvta_shared_yes、cvta_shared_yes_64、cvta_to_shared_yes_64等的目的是啥
c_cpp 垫_
c_cpp -_-公元前
c_cpp uv__next_timeout.c
c_cpp uv__handle_unref.c