If I could I would remove all raw pointers * from my code, because using them may be not thread safe and intentions of the design are not clear (optional value, ownership, etc).
Sometimes however it is not that easy to not use pointers. For example we tend to use pointers for a base type in a container of polymorphic types:
class A : noncopyable { ... };
class B : public A { ... };
std::vector<A*> v;
v.emplace_back(new B);
// temporary container for some operation
std::vector<A*> selected;
if(check())
selected.emplace_back(v.front());
What can you say about above code? Who is the owner? Is it a shared ownership or not? It is why we should probably do that for v:
std::vector<std::unique_ptr<A>> v;
v.emplace_back(make_unique<B>());
Now it is clear that v owns the objects but I still do not like that selected has a raw pointer and makes my design not intuitive. Looking into Standard C++ library I think that there is only one type that could do the job - std::reference_wrapper:
std::vector<std::unique_ptr<A>> v;
v.emplace_back(make_unique<B>());
// temporary container for some operation
std::vector<std::reference_wrapper<A>> selected;
if(check())
selected.emplace_back(*v.front());
How do you feel about that code? Is it a good practice? I know that std::ref() and std::cref where meant to primarily work with templates, but it seems that here we can also use it to clearly state our design intent. The only problem I see is that I have to dereference std::reference_wrapper with get() and there are no operator*() or operator->() inside to have the same interface like in a container with unique_ptr. Should I write something similar on my own? Or maybe a reference_wrapper could be extended for such use case in future C++ versions? Please share your feedback.
EDIT: I changed the code samples to maybe better show the intent.
selected? Is it guaranteed to be destroyed (or emptied) before the objects to which its elements point are destroyed? If so, then use raw pointers: there's no need for shared ownership. There is nothing wrong with using raw pointers in C++; just make sure that raw pointers don't own the pointed-to object.shared_ptr's.selectedandvare meant for. However in a bigger scope/class it is not that easy to see the relationships in a design. In some method you start to work onselectedonly without the view onvand you start to wonder what that pointer here means. Is it an optional value, ownership or just base class pointer? I am looking for a nice way to present my design intent without the overhead in runtime.vhas strict ownership and other potential containers are temporaries to do some operations on the members (ie. sort, subset, etc).