移植Java代码到C++的技巧(整合)
作者:网络转载 发布时间:[ 2013/4/17 9:53:25 ] 推荐标签:
从上面的代码片段我们可以看出,之前的const char* _buffer内部成员变量已经被一个带有引用计数功能的对象取代了。由于为该String类型提供了引用计数机制,因此在getName()函数返回时将仅仅执行对象本身的copy,而其实际包含的缓冲区中的数据将不会发生任何copy的操作,因此这两个对象将在底层共用同一个内部缓冲区地址,直到有任何一个对象发生了数据修改操作,在那时,String类型的数据修改方法将会为要修改的对象重新分配内存,并将原有数据拷贝到该新分配的内存地址中,之后再在新地址上完成的数据修改操作,从而避免了对共享底层数据的其它String对象的数据污染。
前面已经提及过,在绝大多数的应用中,调用者对返回的String对象仅仅是执行读取操作,在此场景下,引用计数机制的引进确实使额外的内存分配和数据拷贝等操作得以避免或延迟发生。事实上,在Java中,如果也遇到同样的修改操作,类似的数据拷贝等动作也将无法避免。后我们给出引用计数类型的代码声明,至于其具体说明,我们将会在之后的专门条目中予以更多的介绍。
class RefCountedBase
{
public:
void addRef() {
//为了保证引用计数器变量在多线程情况下仍然正常工作,
//这里需要添加原子自增锁。
ATOMIC_INC(_refCount);
}
void release() {
//为了保证引用计数器变量在多线程情况下仍然正常工作,
//这里需要添加原子自减锁。
if (0 == ATOMIC_DEC_AND_RETURN(_refCount))
delete this;
}
uint64 getRefCount() const {
return _refCount;
}
protected:
RefCountedBase():_refCount(0) {
}
virtual ~RefCountedBase() {
}
private:
uint64 _refCount; //当前对象的引用计数值。
};
template<typename _TRefCountedObject>
class RefCountedPtr
{
public:
RefCountedPtr():_refObject(0) {
}
RefCountedPtr(const RefCountedPtr<_TRefCountedObject>& otherPtr)
:_refObject(otherPtr._refObject) {
if (NULL != _refObject)
_refObject->addRef();
}
RefCountedPtr(_TRefCountedObject* const otherObjectPtr)
:_refObject(otherObjectPtr) {
if (NULL != _refObject)
_refObject->addRef();
}
~RefCountedPtr() {
if (NULL != _refObject)
_refObject->release();
}
const RefCountedPtr<_TRefCountedObject>& operator=
(const RefCountedPtr<_TRefCountedObject>& otherPtr) {
if (_refObject != otherPtr._refObject) {
_TRefCountedObject* oldPtr = _refObject;
_refObject = otherPtr._refObject;
//在新的对象上面增一
if (NULL != _refObject)
_refObject->addRef();
//在原有的对象上减一
if (NULL != oldPtr)
oldPtr->release();
}
return *this;
}
const RefCountedPtr<_TRefCountedObject>& operator=
(_TRefCountedObject* const otherObjectPtr) {
if (_refObject != otherObjectPtr) {
_TRefCountedObject* oldPtr = _refObject;
_refObject = otherObjectPtr;
//在新的对象上面增一
if (NULL != _refObject)
_refObject->addRef();
//在原有的对象上减一
if (NULL != oldPtr)
oldPtr->release();
}
return *this;
}
operator _TRefCountedObject* () const {
return _refObject;
}
bool operator== (_TRefCountedObject* const otherObjectPtr) const {
return _refObject == otherObjectPtr;
}
bool operator!= (_TRefCountedObject* const otherObjectPtr) const {
return !operator==(otherObjectPtr);
}
_TRefCountedObject* operator-> () const {
return _refObject;
}
private:
_TRefCountedObject* _refObject; //内部托管对象。
};

sales@spasvo.com