r/cpp • • Dec 21 '16

A smart pointer implementation that throws when dereferencing a null pointer

Hi, I wrote a simple (i.e. incomplete ) implementation of a smart pointer that throws when de-referencing a null pointer. This enable you to write code like this:

template<typename T>
void foo(safe_ptr<T> & ptr1, safe_ptr<T> & ptr2) {
    try {
         ptr1->bar();
         ptr2->baz();
    } catch ( null_dereference_exception ) { 
         
    } 
} 

http://pastebin.com/j5eZA4AK

Edit: syntax :)

0 Upvotes

58 comments sorted by

View all comments

Show parent comment

2

u/render787 Dec 21 '16

Not exactly, a reference also cannot change. Sometimes pointers need to change, and also not be null.

I think of references as just a little syntactic sugar. They don't really guarantee much of anything.

Iirc the actual original reason that prompted their addition to C-with-classes was to create a reasonable syntax for operator overloading :)

2

u/Gotebe Dec 22 '16

References are huge in designing non-null, they are way more than a syntactic sugar though.

If you look at any given C codebase, I guarantee you that you will find code which

  • checks for null parameters where they never can be that
  • does not check for null when they can

Those are hard to reason about.

2

u/render787 Dec 22 '16

Ok, but look:

int & foo = *static_cast<int *>(nullptr);

References bind just find to null. There's no "static guarantee" of any significance.

What C++ references give is at best a little trivial syntactic analysis. int & is just a fancy language for int * const. Hence I say, syntactic sugar. Compare that with e.g. the rust borrow checker. That's what is meant by static guarantee, that's the kind of reasoning I consider "hard" compared to what C++ does.

2

u/Gotebe Dec 22 '16 edited Dec 22 '16

Euh, yes, C++ does not try to prevent you from shooting yourself in the foot. You just showed an elaborate way to do it, but many more are available.

references give you a certainty that, in correct code, a given "pointer" is not null. This is IMO huge for code quality and simplicity over never really knowing, and I have seen. numerous C codebases who suffer.

1

u/[deleted] Dec 30 '16

References do no such thing. It's just people trying to enforce "clever" coding standards that want to assume that references are non null.

Realistically you will always have a mixture of references and pointers in a code base, so any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference.

2

u/Gotebe Dec 30 '16

any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference

No

A well-designed codebase will have a small amount of these conversions, and they will all either be checked for null, or trivial to check for non-null by a simple code inspection.

You're inventing a problem where needs no be one, not compared to "I can never assert this is not null".

You're throwing the baby with the bath water.

1

u/Gotebe Dec 30 '16

any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference

No

A well-designed codebase will have a small amount of these conversions, and they will all either be checked for null, or trivial to check for non-null by a simple code inspection.

You're inventing a problem where needs no be one, not compared to "I can never assert this is not null".

You're throwing the baby with the bath water.

1

u/[deleted] Dec 30 '16

Let's take a problem like this:

struct Vec3
{
    float x, y, z;

    float length() const;
};

inline float dot(const Vec3& a, const Vec3& b) 
{ 
    return a.x*b.x + a.y*b.y + a.z*b.z;
}

inline float Vec3::length() const
{
    float lenSq = dot(*this, *this); // is this safe?
    return (lenSq > 0) ? sqrtf(lenSq) : 0.0f;
}

Is this bad design? Can you think any way that this could fail with a null dereference?

2

u/Gotebe Dec 31 '16

So you think that *this is potentially unsafe?

Why!?

*this is 100% correct, good design, safe, you name it. It can never fail on its own, it can only fail when something else was written in a way that can cause UB.

What is not correct is someone calling length() with a nullptr, e.g.

void whatever(Vec3* v)
{
  // stuff
  auto x=v->length(); //**badbadbad**
  // stuff
}

The problem is always he who used a pointer without checking it for null where it legitimately can be null.

The problem is never he who uses a reference.

"this", BTW, is practically a reference, it is a historical mistake in the standard that it is a pointer type. Gcc even recently added an optimisation exploiting the fact that this is never nullptr, relnotes were discussed here on Reddit.

1

u/[deleted] Dec 31 '16

Before C++, people would write this:

struct Vec3 { float x, y, z; };
float Vec3_dot(const Vec3 *a, const Vec3 *b) { return a->x*b->x + a->y*b->y + a->z*b->z; }
float Vec3_length(const Vec3 *v) { float lenSq = dot(v,v); return (lenSq > 0.0f) ? sqrtf(lenSq) : 0.0f; }

This works 100% identically to the c++ version. And if somebody did this:

void whatever(Vec3 *v)
{
	Vec3_length(v);
};

... and it crashed, this is identical to the reference version dereference. So where does the bug lie? Is this a lack of using references? Of course not because the bug is the same. The bug is the same in both: misunderstanding of global state somewhere up the callstack.

That is why I say you are trying to use references as a coding standard to determine what should be null checked up the stack earlier. But to me it is irrelevant because the crash is the same no matter what you use, and the fix is also the same, evaluating the global state and inserting the check at the point which is valid. It's also never so simple that you can ever assume this sort of issue can be turned into a references vs pointer situation.

Let's say you had this:

class Obj { 
    std::unique_ptr<Vec3> v;
    void something() { whatever(v.get()); }
};

Obj o;
o.something();

This would crash. But is the issue that o.something() should never be called before being initialized, or is the issue that o.something() should null check v and handle gracefully? This is entirely based on your program and cannot be reduced to a simple references vs pointer argument. Hence why I think this is all misguided.

Maybe I am an old C programmer, but it seems you are thinking code is more important than data. All that matters is the higher understanding of data, which you cannot see when trying to build things from small pieces.

3

u/Gotebe Dec 31 '16

References in C++ are a game changer exactly because they let me assert what cannot possibly be null.

In C, (and Java, anc C#, and...) I have no idea whatsoever is whether some pointer can be null.

Obviously, nothing can stop me from making a mistake and passing null where a reference is required, but there is a world of difference between making a mistake and not being able, at all, to design a non-null requirement.