Random commentary about Machine Learning, BigData, Spark, Deep Learning, C++, STL, Boost, Perl, Python, Algorithms, Problem Solving and Web Search
Thursday, December 8, 2011
Design a smart pointer in C++
Solution Draft:
reference counter should be shared among all the instance of the pointers referring to the same object. So it's better to dynamically allocate a pointer.
Overloaded question.
ReplyDeleteSmart respect to what? Can be shared? With a movable constructor? Thread safe? It should be able to point to a vector?
valid questions to start an interview. Make your assumptions and start coding ;)
ReplyDeleteLet's forget the thread safety, and let's make it sharable, no copy on write, and it doesn't point to a vector;
ReplyDeletetemplate ;
struct Storage {
Storage(T* aPointer)
: thePointer(aPointer),
theCounter(1)
{}
~Storage() {
assert(theCounter == 0);
delete thePointer;
}
T* thePointer;
size_t theCounter;
}
template
class SmartPointer {
typedef SmartPointer THIS;
public:
SmartPointer(T* aPointer)
:theStorage(new Storage(aPointer))
{}
//copy constructor
SmartPointer(const THIS& aSM)
:theStorage(aSM.theStorage) {
++(theStorage->counter);
}
//assignment operator
SmartPointer& operator=(const THIS& aSM) {
if (this == &aSm) return *this;
if (--(theStorage->counter) == 0) {
delete theStorage;
}
theStorage = aSm.theStorage;
++(theStorage->counter);
}
~SmartPointer() {
if (--(theStorage->counter) == 0) {
delete theStorage;
}
}
const T* operator->() const {
return theStorage->thePointer;
}
T* operator->() {
return theStorage->thePointer;
}
const T& operator*() const {
return *(theStorage->thePointer)
}
T& operator*() {
return *(theStorage->thePointer)
}
private:
Storage* theStorage;
};
Worth to read documentation on Qt blogs about Qt smart pointers (note that they were timely evolved),
ReplyDeletehttp://labs.qt.nokia.com/2009/08/25/count-with-me-how-many-smart-pointer-classes-does-qt-have/