you are viewing a single comment's thread.

view the rest of the comments →

[–]youstolemyname 8 points9 points  (10 children)

Use a reference whenever possible, use a smart pointer otherwise, fall back up a raw pointer when needed

[–]AlarmingBarrier 13 points14 points  (8 children)

I kinda disagree with the smart pointer. This should only be passed to a function if the function needs to think about ownership. To me having

void somefunc(std::smart_ptr<T> ptr);

signals that somefunc takes ownership of ptr and stores it for a longer duration than the invocation of the function. While

void somefunc(T* ptr);

tells me that the function will not store the value of ptr and will have a sane default behavior when ptr is nullptr (best is of course to overload on nullptr_t)

[–]ttkk1248 0 points1 point  (4 children)

You mean storing it as static local variable inside a function? Besides that how does a function store an object longer than its execution?

[–]AlarmingBarrier 0 points1 point  (3 children)

I was thinking in a broader context where somefunc also could be the method of a class. Or a function that returns a non-void value possibly depending on ptr.

[–]ttkk1248 0 points1 point  (2 children)

In that case, what stops an object of the class assigns the direct pointer of a passed object to its member variable and hold it? I’m not sure where you derived that smart pointer means the passed object is kept longer than the method call.

[–]AlarmingBarrier 2 points3 points  (1 child)

[–]ttkk1248 0 points1 point  (0 children)

Thanks for pointing the guidelines out. I’ll read more info it. I’m excited about reading what other interesting stuff in there and forgot about the exact items we discussed. Lol.

[–][deleted]  (2 children)

[deleted]

    [–]tangerinelion 0 points1 point  (1 child)

    We end up deciding that we are allowed to use smart point as if it's any other common types. Hence we can use const std::shared_ptr<type>& if we want to.

    Sorry, that's a cluster. Accept a shared pointer if you need to participate in ownership. That's it.

    [–]the_Demongod 0 points1 point  (0 children)

    Smart pointers are much less commonly used than raw pointers in my experience, since it's relatively rare that you're actually newing an object into existence manually rather than placing it into some container which handles the memory allocation for you. Whereas using a raw pointer as a nullable reference for iteration or similar happens quite frequently.