Citigroup Interview Question
Software Engineer / Developersin the copy constructor, how to implement the reference count? I used an integer for counting the reference, incrementing by 1 when constructing a new shared pointer, decreased by 1 when destructing a shared pointer. but the problem here is how to share the reference count for all shared pointers. obvious i can't use static variable.
It's simple, you can create an inner object with actual stored data and ref count.
template <class T>
public class RefPtr
{
public:
RefPtr(RefPtr& other)
{
if (other != this)
{
other.Release();
other.m_pPtr = m_pPtr;
m_pPtr->m_refCount++;
}
}
RefPtr<T>& operator=(T& data)
{
Release();
m_pPtr = new RefPtrInner();
m_pPtr->m_pData = &data;
m_pPtr->m_refCount = 1;
}
private:
void Release()
{
if (m_pPtr != NULL)
{
m_pPtr->m_refCount--;
if (m_pPtr->m_refCount == 0)
{
if (m_pPtr->m_pData != NULL)
{
delete m_pPtr->m_pData;
delete m_pPtr;
}
m_pPtr = NULL;
}
}
}
typedef struct RefPtrInner
{
T* m_pData;
int m_refCount;
} RefPtrInner;
RefPtrInner* m_pPtr;
};
It's simple, you can create an inner object with actual stored data and ref count.
template <class T>
public class RefPtr
{
public:
RefPtr(RefPtr& other)
{
if (other != this)
{
other.Release();
other.m_pPtr = m_pPtr;
m_pPtr->m_refCount++;
}
}
RefPtr<T>& operator=(T& data)
{
Release();
m_pPtr = new RefPtrInner();
m_pPtr->m_pData = &data;
m_pPtr->m_refCount = 1;
}
private:
void Release()
{
if (m_pPtr != NULL)
{
m_pPtr->m_refCount--;
if (m_pPtr->m_refCount == 0)
{
if (m_pPtr->m_pData != NULL)
{
delete m_pPtr->m_pData;
delete m_pPtr;
}
m_pPtr = NULL;
}
}
}
typedef struct RefPtrInner
{
T* m_pData;
int m_refCount;
} RefPtrInner;
RefPtrInner* m_pPtr;
};
You can use pointer ton an integer for the reference count, in place of using an integer. When creating fresh, new an integer and initialize the reference count to 0. When you copy, you can make the pointer point to the reference count of the original object and increment it by one.
- Arvind.Sinh June 06, 2011