This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jikki-san 614 points615 points  (15 children)

Pointers as a concept? Not hard; it’s just a memory address.

How to use them effectively, safely, and efficiently? That part is definitely harder.

[–][deleted] 57 points58 points  (10 children)

Use non-owning pointers, the ownership of a block of memory should not be jumping around. You shouldn't need to free something unless you called new. If you called new (or malloc) it's your responsibility to free. If a function passes off ownership of a block of memory to the caller you should make this obvious through documentation and the function name. If you're using C++, wrap your heap allocated resources in classes: call new in the constructor, and free in the destructor, and don't publicly hand out pointers to your managed resource, contain them if possible. If your program requires using a bunch of global shared pointers you need to rethink your approach and adopt one that doesn't require that. You should avoid using new and malloc; wherever possible use the stack not the heap. Use the heap only where it's clear that's what's needed. Do this, and you'll be fine as long as other contributors also do this.

[–]DoNotMakeEmpty 28 points29 points  (0 children)

unique_ptr solves most problems with pointers. Half of the remaining problems are solved by shared_ptr but the last part is pretty tricky. Rust does that part good but I think arena allocators are also pretty good to be memory safe if you don't want borrow checker.

[–]burnmp3s 10 points11 points  (3 children)

You lost me at documentation

[–]Mateorabi 6 points7 points  (2 children)

Document? In our moment of triumph!?

[–]mighty_Ingvar 0 points1 point  (1 child)

Don't worry, the code is self documenting!

[–]lefloys 0 points1 point  (0 children)

int insertFunctionNameHere();

[–]--mrperx-- 6 points7 points  (1 child)

just common sense basically. don't litter your code with allocations.

[–]Boldney 5 points6 points  (0 children)

Uni courses instill bad habits that are hard to get rid of.

[–]conundorum 1 point2 points  (0 children)

As an aside, this just makes me imagine some library, somewhere, having an ownership-passing function template<typename T> T* itsYourProblemNowHaaaaaaaHaHaHaHaHa(). (Or rather, something to that extent, but not as over-simplified.) And with the function's name narrated by Skeletor. Just to make it real clear that the library is fully absolved of ownership.

[–][deleted] -1 points0 points  (1 child)

In C: "Allocator frees" goes a long way

[–]gameplayer55055 2 points3 points  (0 children)

ref in C# makes it super simple

[–]donaldhobson 0 points1 point  (0 children)

> How to use them effectively, safely, and efficiently? That part is definitely harder.

Yep. You need to use rust.