shadowmouse > you shouldn't necessarily replace all pointers with unique_ptr and shared_ptr, only those to dynamically allocated memory.
S G H >> I can confirm you don't really need raw pointers since C++11
shadowmouse, +1
Standard library smart pointers can be used in conjunction with custom deleters; so they can handle some RAII scenarios where dynamically allocated memory is not involved. For instance:
1 2 3 4 5 6 7 8 9 10 11
|
#include <memory>
#include <windows.h>
void foo()
{
std::unique_ptr< void, decltype( &CloseHandle ) > temp( CreateWaitableTimer(0,0,0), &CloseHandle ) ;
HANDLE htimer = temp.get() ;
// use timer
// ... (may throw)
}
|
The smart pointers provided by the standard library are not designed to be replacements for all pointers; they are there to provide library support for automated resource management.
Pointers provide an indirect way to refer to an object, which may or may not exist (just as references and reference wrappers provide an indirect way to refer to an object which must exist)
For instance:
int std::stoi( const std::string& str, std::size_t* pos = nullpr, int base = 10 );
The object referred to by
str must exist; so a reference is appropriate.
The object pointed to by
pos may or may not exist; there is no ownership issue involved; and a raw pointer is appropriate.
Raw non-owning pointers continue to be central to C++; C++11 hasn't really changed anything with respect to that. Smart pointers were widely in use in production C++ code, even before C++ was standardised in 1998. C++11 merely added library support for the most common smart pointer usage scenarios.
This is what I tend to follow:
a. reference: a non-reseatable non-owning 'direct reference' to an object which must exist.
b. reference wrapper: a reseatable non-owning 'direct reference' to an object which must exist.
c. pointer: a reseatable non-owning 'direct reference' to an object which may or may not exist.
d. smart pointer: if and only if none of a, b, or c apply. C++11 smart pointers for 'direct reference' with 'deleter' semantics; custom smart pointers for 'indirect reference' semantics.