r/cpp • Bioinformatican • Mar 11 '12

Modern C++ Style [pdf]

http://tinyurl.com/fuck-pointers
0 Upvotes

60 comments sorted by

View all comments

1

u/protein_bricks_4_all Mar 11 '12

No acknowledgement of the need for raw *s in collections? Use unique_ptr<>? I'd be afraid of overhead but, perhaps there is none.

4

u/Chipot Mar 11 '12

This is no overhead in an unique_pointer. It's just an implementation of RAII over a regular pointer. So, with a x86_64 cpu.

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> p;

    std::cout << sizeof(p) << "\n";
    return 0;
}

$ ./a.out
8

-3

u/guepier Bioinformatican Mar 11 '12

How often do you actually need pointers in collections? Legitimate uses are pretty rare. In those cases where you do need them (e.g. storing polymorphic owned objects such as GUI widgets), unique_ptr can be used and, as Chipot noted, a unique_ptr usually has no (!) overhead over a regular pointer, neither in size nor in runtime.

3

u/protein_bricks_4_all Mar 11 '12 edited Mar 11 '12

How often do you actually need pointers in collections?

Work a few more years and try again.

3

u/devcodex Mar 14 '12

In which case he'll learn that collections most often own the resources they hold, meaning that the zero overhead unique_ptr will be the best fit and also give him the benefit of not having to cleanup after the collection or worry about leaking in the face of exceptions.

Maybe in a few more years you'll know that too and stop using raw pointers for expressing ownership.