r/cpp • u/guepier Bioinformatican • Mar 11 '12
Modern C++ Style [pdf]
http://tinyurl.com/fuck-pointers7
u/nowbacktowork Mar 11 '12
Using pointers is not bad. Simply allow smart objects to handle allocations when you can.
Why was std::vector used when the size is known ahead of time and there is no reason for insertions or deletions std::array could have been used here?
-2
u/guepier Bioinformatican Mar 11 '12
Because the slides were meant to be as short as possible, and if the example had used
std::arraythen the objection would have been “but what if I only know the size at runtime?”
std::arraycorresponds toT[constant expression], not to dynamic allocation vianew T[variable].4
u/nowbacktowork Mar 11 '12
But the example shown it was known at compile time not runtime. Since you were touching on some other c++11 enhancements it should have been used here.
-1
u/guepier Bioinformatican Mar 11 '12
The point of the example was to (1) show how to replace
new, and (2) be terse.Point (2) caused me not to put up the following code:
unsigned size = 1024; int* arr = new int[size]();And even here somebody could have objected that “clearly
sizeis known at compile-time, make it aconst(expr)!” Which would have required at least an additional line to fetch a size that is not known at compile time. Two added lines which detract from the actual relevant semantic … for not much gain.
5
u/albeva Mar 11 '12
Rebuttal:
Don't use pointers. This is wrong. Do use pointers where they make sense. In many cases where performance and speed or size are paramount they make the best choice.
Pass by reference. I agree in most cases, but you can't pass a nullptr by reference. SO in many cases this nugget is counter productive.
Returning by value. rvalues make life simpler and improve usability a lot. But rvalues still have overhead a lot of overhead. And in some cases this is not acceptable.
unique_ptr ptr is useful ONLY for immutable ownership. It might be issue with boost scoped_ptr (I think they are the same. just different naming) but you can't remove ptr from it without destroying it.
shared_ptr has a LOT of overhead. its operations are atomic and it maintains a seperate data structure to count references. Stroustrup himself advises against shared_ptr
-1
u/guepier Bioinformatican Mar 11 '12
I don’t think any of the points in your rebuttal has merit. “don’t use pointers” is a very good general rule which may occasionally be violated. My point is that these violations are rare. Much rarer than most people (including you!) seem to think. I’ve programmed a whole (high-performance) parallel programming library without the use of any pointers (I needed a smart pointer at one single location).
In many cases where performance and speed or size are paramount they make the best choice.
This is a common misconceptions. Pointers do not confer speed. In fact, if you want performance it’s often better not to use pointers, forego the indirection and use automatic storage objects. Most cases where pointers are cited as a performance boost, are wrong. E.g. here:
But rvalues still have overhead a lot of overhead.
That’s wrong. In fact, returning an rvalue reference is usually as cheap as returning a pointer. “a lot of overhead” is simply wrong, and by omitting heap allocation, returning rvalue references can actually be faster than returning a pointer to a
newed object.unique_ptr ptr is useful ONLY for immutable ownership
No, you can
resetaunique_ptr. No need for immutability (but immutability in general is a very good idea). Andshared_ptrare definitely not the same asunique_ptr.shared_ptr has a LOT of overhead.
Only for assignment, not for dereferencing which is the most common operation. Furthermore, a
shared_ptrhas exactly as much overhead as required. If you were to implement a thread-safe tracking system for ownership yourself, your system would probably be slower, and never faster.Stroustrup himself advises against shared_ptr
As do I, since they are seldom needed. They should be seen as a last resort. But even Bjarne acknowledges that they fill an important niche.
2
u/albeva Mar 11 '12
As a general rule? yes. but not all inclusive. I don't care what you've coded. I prefer practices that are simple to understand in terms of code being generated. You advocate magic solutions that go way above everyone's head. So we end up with generation of "programmers" who understand nothing about underlying hardware, assembly or what is really good for performance or size. And returning a long will always be faster or at least equal to shared_ptr / unique_ptr or what not.
If a pointer offers least amount of indirection compared to say shared_ptr or container classes or whatnot (and lack of creation of temporary objects) - I'd say it will be faster and more efficient. Simple logic really.
rvalues have more overhead. You need to create a temporary object, call move semantic method and then destroy the temporary object. In all fairness good compiler can optimize this all away, but this is not guaranteed by the standard. And you still need to create an object. So new is called somewhere regradless. And make_shared doesn't play nice if say objects are being allocated from a pool (for instance boost::pool).
And check the scoped_ptr (as I said unique_ptr might have fixed that) you cannot remove object from itr. Calling reset will destroy the old one while swap accepts only another scoped_ptr.
shared_ptr has its uses. but if you pass object around a lot then its not as good. It does have overhead.
In any case I agree to most what you said, but with qualifiers. I prefer to be critical of features used. Its no wonder that we have bloatware around needing gigabytes of ram and gigahertz cpus to run. Its not that this software is all that powerful -its more often than not written with mentality in mind that says so what if it takes few more cycles? what if it takes few more bytes of ram? we did it 5 minutes faster!
1
u/guepier Bioinformatican Mar 11 '12
You advocate magic solutions that go way above everyone's head.
No. I advocate practices that make your code measurably less complex and error-prone. There is no “magic” involved. And your argument that the “code being generated” will be more complex, well, the same is true for any operating system function you’ll use. That’s why we have abstraction, after all. It’s a good thing, otherwise we could never develop complex projects.
So we end up with generation of "programmers" who [don't understand] what is really good for performance or size. And returning a long will always be faster or at least equal to shared_ptr / unique_ptr or what not.
The second sentence here is a prime example of the first sentence: There is more to using pointers than “returning a long”. You incur indirection, and indirection is the performance killer on modern CPUs. Using stack allocation instead of heap allocation + pointer makes a huge difference, so returning an object by value instead of heap-allocating an instance and returning the pointer is more efficient.
Furthermore, a normal
unique_ptrhas the exact same performance characteristics as a raw pointer.rvalues have more overhead.
Again, you are simply wrong. You argue that the optimisations are “not guaranteed by the standard” but this is irrelevant. We are talking about performance here, and the standard generally makes few guarantees about performance, only about correctness. In practice, rvalues have no overhead. Reliably.
And make_shared doesn't play nice if say objects are being allocated from a pool (for instance boost::pool).
Yes, don’t mix different forms of allocation. If you’re using a pool allocator, you don’t need smart pointers.
I prefer to be critical of features used. Its no wonder that we have bloatware
None of the features here (with the possible exception of
shared_ptr) is “bloatware”. These are simple features which generate efficient code. C++ is in the unique situation that it can offer high-level abstraction without incurring any cost at all. If you don’t take advantage of that you can as well program in C.Its not that this software is all that powerful -its more often than not written with mentality in mind that says so what if it takes few more cycles? what if it takes few more bytes of ram? we did it 5 minutes faster!
This is why I explicitly mentioned the project I’ve worked on, which you’ve been so dismissive of. Because this mentality has nothing to do with the use of high-level features in C++, on the contrary. The slides do not advocate writing inefficient code.
Your comments showcases precisely what I wanted to address: the misconception that high-level code is necessarily inefficient.
2
u/albeva Mar 11 '12
Like I said in general I agree to your suggestions. With qualifiers. There are circumstances when its not desired. In any case I concede maybe I am tad too critical of new additions and haven't had enough time to test things out myself. In any case out of curiosity is your project you mentioned open source? Can I take a look?
-1
u/guepier Bioinformatican Mar 11 '12
Uh, sore point. ;-) Yes, in principle the project is Open Source (it’s supposed to be part of the SeqAn library). However, due to a major API rewrite in the surroundnig library the parallel programming part isn’t public at the moment until it’s rewritten, and I currently have no time to do so, and it’s on another machine. :-(
2
u/m1ss1ontomars2k4 Mar 11 '12
huge_object build_new_object() {
huge_object ret;
…
return ret;
}Is this even possible? Won't ret go on the stack? Or does it go on the heap instead? Unfortunately I'm no C++ expert.
6
u/guepier Bioinformatican Mar 11 '12
It’s definitely possible (if it weren’t, C++ would be fundamentally and irredeemably crippled as a language). Semantically, the stack object is simply copied upon return so accessing it outside is no problem at all. What’s more, all (!) modern compilers optimise this copy away reliably in almost all situations – C++11 move constructors take care of those remaining ones. So this is both safe and efficient.
4
Mar 11 '12 edited Mar 11 '12
The term return value optimization refers to a special clause in the C++ standard that allows an implementation to omit a copy operation resulting from a return statement, even if the copy constructor has side effects, something that is not permitted by the as-if rule alone.
Absolutely amazing and unexpected! But I guess your copy shouldn't do more than just copy... even updating the object count (if you have a static instance count in the class) doesn't need to be done by the copy constructor if the stack object is returned in this way rather than creating a new object, since the default constructor/whatever will do that when the object is created.
1
u/m1ss1ontomars2k4 Mar 11 '12
Derp, for some reason I was thinking about how you can't, say, do something like this in C:
int * foo () { int a = 1; return &a; }Yeah, my comment didn't really make sense.
8
u/haohaolee Mar 11 '12
Actually the so called "don't use fxxxing pointers" means "don't use raw pointers which need delete or similar release operations". and more, this slide just tells people not to use pointers as possible as they can and provides some suggestions. It doesn't mean totally giving up pointers. Why don't some people understand this but cavil
2
u/Breepee Mar 11 '12
Is there some tutorial for what you mean? I know shared/unique/etc pointers exist, but I don't know much more than that...
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_ptrcan be used and, as Chipot noted, aunique_ptrusually 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.
1
u/JonKalb CppCon | cpp.training Mar 11 '12
Nice.
I think you should avoid "new" and you can do this by using std::make_shared() and sutter::make_unique().
1
u/albeva Mar 11 '12
make_unique is not part of the standard library
0
0
Mar 13 '12
[deleted]
1
u/guepier Bioinformatican Mar 13 '12
Wrong on all counts. In fact, the slides are pretty much echoing the consensus among many C++ experts. This is easily testable: just watch some of the “Going Native 2012” sessions or see what experts in comp.lang.c++.moderated or on Stack Overflow have to say.
If you think that memory allocation, or the distinction between stack and heap has got anything to do with this, you’ve still got a lot to learn about C++. The slides are about resource management (i.e. deallocation), not memory allocation.
18
u/filox Mar 11 '12
Try implementing a tree without pointers.