-1

I've a little question for all C++ coders ! For you, is it compatible to "C++ philosophy" to recode your own smart pointers. Actually I use shared_ptr with weak_ptr for a project but it's complicate too much the code. I could use of course raw_ptr, but ... it's "plain c" ... So what are you think about it ? Should I recode my own smart pointer or continue to use shared_ptr with weak_ptr

hexa
  • 11
  • 1
  • 3
    It could help if you look at the smart pointers in terms of *ownership* instead of simply self-deleting pointers. Who *owns* a resource? Can the resource be owned by only one, or is the ownership shared? Or is there no ownership involved at all? – Some programmer dude Apr 03 '18 at 10:48
  • 8
    What would your own smart pointer solve that `shared_ptr` and `unique_ptr` don't already solve? – bolov Apr 03 '18 at 10:49
  • You should see [Herb Sutter's lecture](https://www.youtube.com/watch?v=JfmTagWcqoE). It should sort out the concepts nicely for you. – StoryTeller - Unslander Monica Apr 03 '18 at 10:56
  • @bolov -- you start with the fact that you can't create a shared_ptr from this. So now you have to use `enable_shared_from_this`. So, at this point, might as well use a super-root. Still shared_ptr doesn't implement destructor callbacks. It might also be null, so you can't enforce a contract valid non-null smart pointer, using the C++ library's implementation. Then, the C++ library's implementation of `const`-ness, related to smart pointers, requires a temporary when passing a smart ptr to a mutable object as a param that takes a smart ptr to a const object. – Sam Varshavchik Apr 03 '18 at 11:00
  • There is an implicit part to your question: should you use raw-pointers over smart pointers in the case the latter leads to over-complexity? I'd say yes. In some graph-like data structures, for instance, managing memory and ownership at the same time isn't the best idea, so raw pointers still have their place. – papagaga Apr 03 '18 at 11:09
  • 2
    What is it exactly that makes the code complicated? Smart-pointers are quite straightforward to use. Are you using the right one, and are you using it right? Give an example of something you think is needlessly complicated, preferable in code. – sp2danny Apr 03 '18 at 11:21
  • 1
    The question lacks a premise. You seem to be suggesting that you want to write your own non-smart smart pointers, but that is contradictory and cannot be the case. – Lightness Races in Orbit Apr 03 '18 at 11:39

1 Answers1

5

is it compatible to "C++ philosophy" to recode your own smart pointers

No, it's unnecessary and a waste of time. The Standard Library provides smart pointers, and the Standard Library is available in every conforming implementation.

Unless you have a very good reason to not do so, use <memory>.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416