I read in a few articles that raw pointers should almost never be used. Instead they should always be wrapped inside smart pointers, whether it\'s scoped or shared pointers.
There can be many reasons. To list few of them:
Edit: Using smart pointers is a completely developer's choice. It depends on various factors.
In performance critical systems, you may not want to use smart pointers which generates overhead
The project which needs the backward compatibility, you may not want to use the smart pointers which has C++11 specific features
Edit2 There is a string of several downvotes in the span of 24 hours because of below passage. I fail to understand why the answer is downvoted even though below is just an add-on suggestion and not an answer.
However, C++ always facilitates you to have the options open. :) e.g.
template
struct Pointer {
#ifdef
typedef std::unique_ptr type;
#else
typedef T* type;
#endif
};
And in your code use it as:
Pointer::type p;
For those who say that a smart pointer and a raw pointer are different, I agree with that. The code above was just an idea where one can write a code which is interchangeable just with a #define, this is not compulsion;
For example, T* has to be deleted explicitly but a smart pointer does not. We can have a templated Destroy() to handle that.
template
void Destroy (T* p)
{
delete p;
}
template
void Destroy (std::unique_ptr p)
{
// do nothing
}
and use it as:
Destroy(p);
In the same way, for a raw pointer we can copy it directly and for smart pointer we can use special operation.
Pointer::type p = new X;
Pointer::type p2(Assign(p));
Where Assign() is as:
template
T* Assign (T *p)
{
return p;
}
template
... Assign (SmartPointer &p)
{
// use move sematics or whateve appropriate
}