Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
You need to overload operator *
If you do not need to keep the exact number of reference count, the SharedIntPtr class roughly looks like this:
class SharedIntPtr{
SharedIntPtr *prev;
SharedIntPtr *next;
int *value;
};
All pointers to the same int value form a doubly linked list. The constructor sets the int pointer and add itself into the linked list. The reset() function removes itself from the linked list. If the linked list becomes empty, it frees the memory. At last, it sets the int pointer to NULL.
However, if the exact number of reference count is needed, you need an additional wrapper class to wrap the int value and the reference count together, so each SharedIntPtr object can access these two values.
The reference count needs to be stored in heap and the sharedpointer object should have a pointer to it...
--.h file
class SharedPointer{
public:
int* value;
int* reference;
SharedPointer();
SharedPointer(int*);
SharedPointer(const SharedPointer&);
void reset();
int& operator * (void) const;
};
--.cpp file
SharedPointer::SharedPointer(){
value = nullptr;
reference = new int(0);
}
SharedPointer::SharedPointer(int* n){
value = n;
reference = new int(1);
}
SharedPointer::SharedPointer(const SharedPointer& other){
value = other.value;
reference = other.reference;
*reference += 1;
}
void SharedPointer::reset(){
*reference -= 1;
if(*reference == 0)
delete value;
value = nullptr;
reference = nullptr;
}
int& SharedPointer::operator*(void) const{
return *value;
}
class SharedIntPtr{
ref_int* ref;
public:
SharedIntPtr(int *arg)
{
ref = new ref_int;
ref->ptr = arg;
ref->rc = 1;
}
SharedIntPtr(SharedIntPtr &arg)
{
ref = arg->ref;
}
void reset()
{
rc--;
if( rc == 0 )
{
delete ref;
}
ref = 0;
}
int& operator *()
{
if( ref )
return * (ref->ptr);
else
return 0;
}
};
is "*a = 2" possible without casting data type?
- anonymous January 24, 2013