A: A smart pointer is a C++ class which mimics a regular pointer in syntax and some semantics, however it does more. Since smart pointers to distinct types of objects tend to have a lot of code in common, approximately all good-quality smart pointers in existence are templated trhough the pointee type, as you can notice in the following code:
template
class SmartPtr
{
public:
explicit SmartPtr(T* pointee) : pointee_(pointee); SmartPtr& operator=(const SmartPtr& other);
~SmartPtr();
T& operator*() const
{
...
return *pointee_;
}
T* operator->() const
{
...
return pointee_;
}
private:
T* pointee_;
...
};
SmartPtr aggregates a particular pointer to T in its member variable pointee_. Most smart pointers do this. In some of the cases, a smart pointer may aggregate some handles to data and compute the pointer on the fly.
The two operators give SmartPtr pointer-like semantics and syntax. i.e., you can write
class Widget
{
public:
void Fun();
};
SmartPtr sp(new Widget);
sp->Fun(); (*sp).Fun();
Sideways from the definition of sp, nothing reveals it since not being a pointer. It is the mantra of smart pointers: You can replace pointer definitions along with smart pointer definitions without incurring major changes to your application's code. Thus you get extra goodies along with ease. Minimizing code changes is extremely appealing and essential for getting large applications to employ smart pointers. However, smart pointers are not a free lunch.