PayPal Interview Question
Developer Program EngineersCountry: -
Interview Type: In-Person
Idea is something like this:
struct
{
char * ptr;
u32 count;
}smart_ptr
retain()
{
count++;
}
release()
{
count--;
if(count == 0)free(ptr);
}
In my view examiner might be more interested in knowing what will be the lay out of the class. Smart pointer class shall contain the overloaded operators for * and -> a destructor and constructor
this is smart pointer implementation...
correct me if any thing is worng.....
template <class T>
class sPointer
{
public:
sPointer(T *p = 0):ptr(p){}
~sPointer(){delete ptr;}
T* operator->(){ return ptr; }
T& operator*() { return *ptr;}
T* get() { return ptr;}
sPointer(T &obj)
{
cout<<"auto copy constructor"<<endl;
this->ptr = obj.ptr;
obj.ptr = NULL;
}
T& operator=(const T & obj)
{
if(this->ptr != obj.ptr)
{
ptr = obj.ptr;
obj.ptr = NULL;
}
return *this;
}
private:
T *ptr;
};
This is example of shared obj....
if any thing is wrong plz correct me.
//reference count class to count the no of obj’s created
class refCount
{
int count;
public:
void incrCount(){count++;}
int decrCount(){ return --count;}
};
template <class T>
class sPointer
{
private:
T *ptr;
refCount *rCount;
public:
sPointer(T *p = 0):ptr(p),rCount(0)
{
rCount = new refCount();
rCount->incrCount();
}
~sPointer()
{
if(rCount->decrCount() == 0)
{
delete ptr;
delete rCount;
}
}
// copy constructor
sPointer(const T & obj) : ptr(obj.ptr)
{
rCount = obj.rCount;
rCount->incrCount();
}
//overload assignment operator
T& operator=(const T & obj)
{
if(this->ptr != obj.ptr)
{
ptr = obj.ptr;
rCount->incrCount();
}
return *this;
}
T* operator->(){ return ptr; }
T& operator*() { return *ptr;}
};
//this is example class
class B
{
private:
int a;
public:
B(int aa = 0):a(aa){cout<<"B - constructor"<<endl;}
~B(){ cout<<"B dest"<<endl;}
void disp() { cout<<"show - "<<a<<endl; }
};
// main prog
int main()
{
B *obj = new B(100);
obj->disp();
//creating the shared pointer
sPointer<B> obj1(obj);
obj1->disp();
sPointer<B> obj2;
//overload assignment operator called
obj2 = obj1;
obj1->disp();
obj2->disp();
// when objs count is zero then only obj will be deleted
return 0;
}
Many of the earlier solutions are wrong because they don't properly update the count. The count variable has to be a single value that is shared among all copies of the same pointer. It should therefore be an int* allocated on the heap when the pointer is first created (via a T* object and not via copy constructor). Otherwise, old copies of the smart pointer won't know about new copies that may be floating around and may prematurely de-allocate the object.
Here's some code:
- eugene.yarovoi October 02, 2011