21 ms·
My favourite C++ footgun
- fooker 5y agoThat’s not a valid evaluation order, afaik. You can not start evaluating one argument, stop and switch to the other, then come back to the earlier one.
- MaxBarraclough 5y agoDo take a look at dvt's comment. Prior to C++17, it was a valid evaluation order.
- bregma 5y agoPrior to C++17 such an evaluation order would have violated the standard. ISO/IEC 14882:2011 1.9/13 [Note: Indeterminately sequenced evaluations cannot overlap, but either could be executed first. — end note]. The arguments in a faction call are a comma-separated indeterminate sequence (5.2.2/4 [Note: Such initializations are indeterminately sequenced with respect to each other (1.9) — end note]).
- ectopod 5y agoIs there any version of C++ in which this interleaving is permitted?
- quietbritishjim 5y agoThe full context to that second quote is: > When a function is called, each parameter ([dcl.fct]) shall be initialized ([dcl.init], [class.copy], [class.ctor]) with its corresponding argument. [ Note: Such initializations are indeterminately sequenced with respect to each other ([intro.execution]) — end note ] So it's only about initialisation of parameters from arguments, not to the evaluation of arguments. (For example if foo() takes a std::string parameter, and bar() returns a const char*, then in the expression foo(bar()) the above quote refers to the call to the string constructor, not to the call to bar().) The more relevant part is 5.2.2/8: > [ Note: The evaluations of the postfix expression and of the argument expressions are all unsequenced relative to one another. All side effects of argument expression evaluations are sequenced before the function is entered (see [intro.execution]). — end note ]
- MaxBarraclough 5y ago> Prior to C++17 such an evaluation order would have violated the standard Herb Sutter disagrees. [0] The C++ legalese you've quoted seems decisive, unfortunately Sutter's post doesn't mention it. See also [1][2]. edit quietbritishjim beat me to it, and with a better informed comment to boot. [0] https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/ https://herbsutter.com/2013/05/29/gotw-89-solution-smart-poi... (ctrl-f for known, and see also the comment thread at the bottom of the page) [1] https://stackoverflow.com/a/48844115/ https://stackoverflow.com/a/48844115/ [2] https://stackoverflow.com/a/46472497/ https://stackoverflow.com/a/46472497/
- Woansdei 5y agoIt may be valid, but I don't see any value in doing it, and it would take extra code in the compiler (and possibly the resulting binary). So did any compiler actually do that?
- MaxBarraclough 5y agoIt's anecdotal, but apparently it really has happened. Here's the comment by dataflow: https://news.ycombinator.com/item?id=27600894 https://news.ycombinator.com/item?id=27600894
- fooker 5y ago"What can be asserted without evidence can be dismissed without evidence."
- CraigJPerry 5y agoA capturing lambda is another way to leak a std::shared_ptr<> - i feel like it's an even easier way to run into this kind of footgun but i suppose it depends whether you typically use lots of lambdas. A reasonable solution in my case could be to use std::weak_ptr<> instead but that wouldn't be useful here.
- quietbritishjim 5y ago> A capturing lambda is another way to leak a std::shared_ptr<> How so? Do you mean if you do exactly what the article says when initialising the capture variables? Or something lambda specific?
- quietbritishjim 5y agoThis question was genuine curiosity so I'm a bit disappointed there was never a reply. On reflection, I suspect the parent comment was referring to creating circular dependencies using lambdas and std::function. For example, a class Inner wants allow notifying its owner when events happen, so it has a std::function member variable it uses for the callback function, and a class Outer has an instance of Inner as a member variable. But then passes as a callback: m_inner.set_callback([self=this->shared_from_this()](Param p){ self->handle_inner(p); }); Now Outer owns Inner (directly) and Inner holds a shared_ptr to Outer, so Outer will never be destroyed (and therefore neither will Inner).
- overgard 5y agoMy (least) favorite footgun is "auto" when it comes to references. If you want to get a pointer from something, you would write this: auto fooPtr = mywidget.getPtr(); fooPtr->doCoolStuff(); But we all know references are better than pointers right? So we should just write... auto fooRef = myWidget.getRef(); fooRef.doCoolStuff() The problem is... this is valid and will probably not do what you want. It will make a copy. What you want is actually auto& fooRef = myWidget.getRef(); I once spent an entire day debugging a bizarre crash because of that. I was asking for a reference to a scene graph, and what was actually happening is I was getting a clone of the scene graph (which was an object that couldn't be safely copied), and then destroying a bunch of shared pointers when the function returned. Fun times.
- bregma 5y agoWait, you had an object that was unsafe to copy, but you told the computer it was safe by not deleting the copy constructor? I guess it should have done what you wanted, not what you told it.
- secondcoming 5y agoNo, everyone gets LHS auto wrong at the start. They don't realise it makes a copy. I have to point it out every other code review.
- jcelerier 5y agoThe rule is simple: auto behaves like a template parameter
- Koshkin 5y agoAh, templates... Universal references... Good stuff.
- Kranar 5y agoYep, except now we're supposed to call them forwarding references because the motivation Scott Meyers had for naming them universal references turned out to be incorrect in subtle ways. Even the notable experts get things wrong when it comes to how complex and bloated C++ is.
- dvt 5y agoThe nested function execution interleaving blew my mind (imagine having to debug that), so I had to look it up. Apparently, interleaving is prohibited in C++17 onward. So this: > The second one is there since this is C++, priority() might raise an exception, meaning that new Widget will be called, but never passed to std::shared_ptr, and thus never deleted! Is now impossible (thank God!). See a full SO discussion here[1]. Stuff like this makes me so happy I don't write C++ anymore, but the gist of it is (from the standard): > For each function invocation F, for every evaluation A that occurs within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any), either A is sequenced before B or B is sequenced before A. [1] https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17/46472497#46472497 https://stackoverflow.com/questions/38501587/what-are-the-ev...
- TwoBit 5y ago> Is now impossible I don't see how that is so. C++ 17 allows new Widget to complete and then the priority() call to execute and throw before both are passed to shared_ptr(), thus creating a leak. Your cited example [1] doesn't leak because both arguments are shared_ptr. Seems to me that C++ 17 does indeed solve this latter case but not the former.
- nyanpasu64 5y ago> both are passed to shared_ptr() priority() is not passed to shared_ptr(), only to processWidget().
- dvt 5y agoPer [1]: > evaluations of A and B are indeterminately sequenced: they may be performed in any order but may not overlap: either A will be complete before B, or B will be complete before A. The order may be the opposite the next time the same expression is evaluated. And: > 21) Every expression in a comma-separated list of expressions in a parenthesized initializer is evaluated as if for a function call (indeterminately-sequenced) Emphasis mine. What the above basically says is that in the case of some function `f(A, B)`, the arguments `A`, and `B`, are what's known as "indeterminately-sequenced" -- this mean that their execution cannot be interleaved (overlap) -- but they still individually execute in a non-deterministic order (A before B, and sometimes B before A)! With that said, the good news is that B can now never throw in the middle of A, which is precisely what we have in OP's example. [1] https://en.cppreference.com/w/cpp/language/eval_order https://en.cppreference.com/w/cpp/language/eval_order
- MaxBarraclough 5y agoOne of my favourites too. Here's a good StackOverflow answer on the topic. [0] Looking here [1] though, did something change in C++17 to ameliorate things? edit Turns out yes, see dvt's comment. Second edit Apparently [2] I knew this 3 years ago and forgot. [0] https://stackoverflow.com/a/7693775/ https://stackoverflow.com/a/7693775/ [1] The final bullet-point in the Notes section of https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared https://en.cppreference.com/w/cpp/memory/shared_ptr/make_sha... [2] https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17#comment89394778_46472497 https://stackoverflow.com/questions/38501587/what-are-the-ev...
- jeffbee 5y agoThis way to call a function smells wrong anyway. A shared pointer to a new value is nonsense as a parameter, because at the point of the call the pointer is not shared, it is unique! Since a shared pointer is implicitly constructible from a unique pointer, this makes more sense, assuming there are other call sites that really intend to share ownership: void frob(std::shared_ptr<T>); main() { frob(std::make_unique<T>()); }
- Koshkin 5y agoWell, usually you designate a pointer as 'shared' not only when it happens to be already shared but also when it will be shared later on.
- ot 5y agoIf you know that the pointer is going to be shared, it's more efficient to use `make_shared` as it will use a single allocation for both the object and the control block.
- Kranar 5y agoYou've now forgone an important optimization opportunity for absolutely no benefit.
- dzdt 5y agoThere is a mental optimization to be had by using only a subset of the language. If you can get by using fewer constructs (and work on code with like-minded authors) you can better learn to use them correctly and save on thought as to which is the most optimal approach in every case.
- Kranar 5y agoGreat, so stick to the subset of providing a function that asks for a shared_ptr with a shared_ptr instead of introducing unique_ptr as an additional construct. This way you get the benefits of the optimization and don't need to add the overhead of thinking about how shared_ptr will take a unique_ptr and perform a conversion on it. If something takes a foo, give it a foo.
- throwaaskjdfh 5y agoWhy does it seem like C++ is constantly replacing its subtle hazards with even more subtle hazards? It's like they never go away, they just turn into something more obscure.
- Koshkin 5y agoWell, no doubt it all comes from good intentions. (With which, you know, the road to hell is paved.)
- plorkyeran 5y agoThis is an example of a very old subtle hazard that has been removed entirely (the ordering which causes problems is no longer permitted in C++17).
- deleted 5y ago[deleted]
- pshc 5y agoIt’s Stroustrup’s Full Employment Theorem in action.
- AnimalMuppet 5y agoIn addition to what plorkyeran said, "more obscure" can mean either "harder to understand" or "less often encountered". The second one is progress.
- Kranar 5y agoBecause the people involved with C++ have a toxic aversion to learning from other languages. Anytime issues are brought up the people involved with C++ standardization keep yapping the line that "But C++ is not like <other language>." and then proceed to implement a half-assed version of what other languages have and then 2-3 years later people find all kinds of footguns that could have simply been avoided had proper research been performed. The big issue is that becoming involved in the C++ standardization process is purposely arcane, requiring people to physically travel to remote locations, miss time off work, and spend a lot of money. There are literally substantial language features added to C++ that are nothing more than the work of maybe 3-4 people. These features could have benefited enormously from having 100s, if not 1000s of potential developers exercising use cases and contributing suggestions, but the standardization process is heavily gated.
- ot 5y agoIn modern C++ the use of `new` and `delete` should be considered smell, for this and other reasons.
- eklitzke 5y agoThe author writes "this might be why there is std::make_shared", but that's not really why it exists. When you create a std::shared_ptr it needs to allocate memory for a control block structure (which tracks the reference count) as well as the memory for the object itself. If you write std::shared_ptr<Foo>(new Foo) this will result in two memory allocations, one for the Foo object and the other for the std::shared_ptr control block. If you write std::make_shared<Foo>() then a single allocation will happen which has enough space for both the control block and the Foo object, and then placement new is used to initialize the memory for both structures. So std::make_shared exists to reduce the number of memory allocations that are being made, not for the reason suggested here.
- asveikau 5y agoI think the idea that you are also relying on a presumably well tested library to get the exception corner cases right is also noteworthy. Memory leaks on allocation failure are pretty common in naive code, and a good thing to handle in a library where it can get well thought out.
- Koshkin 5y agoThis is very important. Try to hide most of complexity in a library, and then unit-test the hell out of it.
- haldean 5y agoThere's a crazy downside to make_shared that I learned recently because of this: if you have a weak pointer to a shared thing, and the refcount for the shared thing drops to zero, the weak pointers will keep the allocation for the object "alive", because they still need access to the remnant and the remnant was created in the same allocation as the object so they can't be freed separately. So now I only use make_shared if I know for sure there won't be a weak_ptr pointing at it (or if the base object has a relatively small memory footprint after it's been destructed).
- ot 5y ago
- 2bitencryption 5y agoMy favorite C++ footgun is creating a Vector with some items, taking a reference to, say, &vec[3], then adding another item to the vec, then trying to use the reference from the previous step. If you write C++ it might be obvious what the problem is. If you don't, this will absolutely ruin your entire day. The worst part is, 95% of the time, it will probably work without issue. But eventually, pushing a new item to the Vector will trigger a relocation of the whole vector, which will invalidate your reference and bring down production. Have fun debugging that.
- nicoburns 5y agoYep. I learnt about this when I was learning Rust (which makes this a compile-time error). I was very glad I didn't have to learn this and the 100 other things like that seem to exist in C++ the hard way!
- failwhaleshark 5y agoFootguns might keep you prepared for the zombie apocalypse, but they'll inevitably make it difficult to walk. I'm glad I don't currently use C++ in production, but that may change soon. ):
- krylon 5y agoYou can run into the same problem in C, using malloc/realloc. realloc, in fact, makes for a nasty footgun, too (and remains, of course, available in C++).
- turminal 5y agoYes, but unlike with realloc and a custom dynamic array, C++ references and smart pointers and containers are half-smart and do all sorts of things on their own. Knowing when they will and when they will not be "smart" makes writing C++ really difficult sometimes.
- flohofwoe 5y agoAn important difference is that in C it is usually obvious that a reallocation is happening while in the C++ stdlib, memory management is usually hidden (important to note that this isn't a design fault of the C++ language, but of the C++ stdlib, unfortunately the two are more and more entangled in newer C++ versions). Because of the fact that memory management is hidden in C++, I find claims that C++ is more memory-safe than C quite hilarious. If it works, it works fine, but if anything goes wrong (which is quite easy to achieve) it's much harder to find the actual problem in C++ than in C.
- liquidify 5y agoAny raw new in code is a smell. I thought this was old news?
- astrange 5y agoI've noticed that every few years when I look at C++ again, everyone says this about whatever was correct last time.
- clappski 5y agoPretty sure that raw new has been a smell since C++11, 10 years ago, since the introduction of smart pointers that aren't terrible. Maybe longer than a few years since last time you looked at it!
- gpderetta 5y agoNon-terrible smart pointers existed well before that (no, auto_ptr doesn't count), so naked new and delete have been code smell for a while.
- astrange 5y agoYes, one time I looked and people were saying new was bad and to use auto_ptr, and then the next time I looked everyone was saying that had never happened.
- rileymat2 5y agoIf you try to use inheritance, object slicing by far. I understand the practical reasons for it, but it feels very wrong.
- ncmncm 5y agoIt only ever comes up in toy examples. Working programmers do not encounter it, so in practice it is never the cause of a problem.
- TinkersW 5y agoSlicing requires you to treat a reference type as a value type, nobody who knows C++ does this, so slicing is pretty much restricted to people coming in from Java land or similar. I've not encountered a single instance of slicing in 10+ years of C++.
- towergratis 5y agoThe real problem is not specific to C++, memory or shared pointers, but as the author mentions later, the fact that "function parameters evaluation order is unspecified". The problem is similar in C as well. `printf("%d, %d", i++, i++);` will give you different results depending on the compiler.
- Koshkin 5y agoThe situation is even worse, due to the possible interleaving of the execution of function calls.
- towergratis 5y agoThe root cause is the same
- Koshkin 5y agoWell, except that C does not have exceptions (at least not in the way that C++ does).
- jhgb 5y agoHow is it "the same"? If the evaluations of the individual arguments can't overlap, then the C example's problem still exists while the C++ example's problem doesn't. And if the order of evaluation were guaranteed but the evaluations could overlap, the C example wouldn't have a problem but the C++ example still would. To me the two problem's causes seem quite different.
- yongjik 5y agoI think it's basically the same problem as unique_ptr? This is the best explanation I've seen: https://herbsutter.com/gotw/_102/ https://herbsutter.com/gotw/_102/
- _huayra_ 5y agoJumping on the footgun bandwagon, one I had always known, but never realized how bad of a design decision it was was "the c++ rvalue lifetime disaster" [0]. The talk linked in [0] has a different conclusion, but describes the problem well. Basically, the lifetime aspects of r/l-values are improperly coupled to the "can I scavenge the internals?" aspect (via const). R-values should not have been promoted to const-ref (I think it was a legacy behavior?) because then this const-ref can be passed around (e.g. returned) as if it were going to outlive the original reference's frame! This was the first time I realized what a mess C++ can be (although I still use it a lot). This is a subtle error that I have seen seasoned experts miss in code review (especially in templated code). You can't work around it like you can the underperforming parts of the stdlib (Abseil and Folly help out a lot!). This promotion choice of auto&& -> auto const& is really baked into the language and I don't see a path to change it. The other "biggest foot cannon" has gotta be the incredibly subtle ways one can violate the ABI, e.g. executable A linking against libs B and C, each of which bundle an ABI-incompatible implementation of the same parent dep D (versions 1.1 and 2.1). You never know which type of object you're really passing around with D::SomeType! [0] https://quuxplusone.github.io/blog/2020/03/04/rvalue-lifetime-disaster/ https://quuxplusone.github.io/blog/2020/03/04/rvalue-lifetim...
- pwdisswordfish8 5y ago> "the c++ rvalue lifetime disaster" why is it always C++ people that come up with those dramatic-sounding names
- gpderetta 5y agoBinding temporaries to const was a very very very old decision and it is relied on pervasively, so it would have been very painful to break. For more existential horrors, VC6 as an extension used to allow binding temporaries to non-const references!
- user-the-name 5y agoWell, here we have an entire thread of nothing but reasons to never write anything in C++. Jesus christ, what an utter mess of a language.
- chrismsimpson 5y agoI was toying with the idea of writing a transpiler from C++ and this thread has thoroughly nixed that idea.
- pjmlp 5y agoAny language with 40 years of history, and great care for backwards compatibility, shares a similar mess.
- user-the-name 5y agoC has a longer history, and is not even 10% of the horrific mess that C++ is.
- pjmlp 5y agoYou clearly only use either GCC or clang C, without much knowledge of WG14 documents. Also some of the C++ horrors are caused by the consequences to stay copy paste compatible with said documents and tooling across all platforms where a C compiler exists.
- user-the-name 5y agoThe compiler implementation has no bearing on whether the spec is a mess or not. The C++ spec is horrendous, even when implemented 100% correctly.
- pjmlp 5y agoJust like the C spec with 50 years of history, again it just proves you don't know that you are talking about. Go read some WG14 stuff then come back to us.
- dale_glass 5y agoMy favorite: slicing. That one blew my mind when I found out. You can rip off a chunk of an object by accident... and nothing happens whatsoever. There's no warning from the compiler. You can stuff a Derived into a std::list<Base>, it'll work just fine, and if Derived happened to say, hold a pointer, it'll happily vanish into the ether. Besides the amount of confusion that can ensure from this, it means you can have problems if you want to introduce inheritance into a place that didn't have it before. Especially if it's some sort of external component. You think you're clever inheriting from a framework class and adding some data on top? Nope, the internal structure you don't control doesn't want to cooperate with that plan.
- jcelerier 5y ago> There's no warning from the compiler You can use clang-tidy to warn / error on that: https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-slicing.html https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidel...
- slavik81 5y ago> You can rip off a chunk of an object by accident... and nothing happens whatsoever. There's no warning from the compiler. Slicing is a bad name for this phenomenon, because what you've described is what the name implies, but that is not what is happening. The original object is completely unchanged. Nothing was ripped off of it. Constructors create new objects.
- gpderetta 5y agoI think slicing gets a bad name because of the old pervasive OOP mentality. Slicing is perfectly fine and expected in a value-type oriented program.
- IncRnd 5y agoThere are so many areas in C++ that are footguns. Heck, it sometimes is non-obvious what A=B; does.
- pjmlp 5y agoA.operator=(B) Hardly any different that knowing what func(A, B) does.
- dthul 5y agoMy guess is that the parent poster meant something more like: it's hard to tell whether A=B will deep copy, shallow copy or move the right hand side and which operator=() will actually be called. First you need to figure out the types of A and B and their "modifiers" (like const or references) to start figuring out which operator=() could potentially be called. That might still be very hard to do if for example there are implicit conversions from B to some other type involved. Such conversions can depend on code which might be nowhere close to where the operator=() is defined.
- pjmlp 5y agoWell, what happens when you call func(A, B) if both are pointers in C? Or if we take an Algol derived language, like Pascal or Modula-2, func might have been defined as, type my_complex_type = .... procedure func(var a, b:my_complex_type); begin end; Raising the same kind of questions. Yes there are issues with C++ approach as you describe, however sometimes it seems C++ hate kind of blinds the people that similar issues occur in other languages to some extent.
- gpderetta 5y agoSpeaking of Algol and argument passing, I'll leave this [1] here... [1] https://en.wikipedia.org/wiki/Man_or_boy_test https://en.wikipedia.org/wiki/Man_or_boy_test
- gpderetta 5y ago
- FpUser 5y agoHa. When looking at the example I did not realize what is really wrong with it for quite a while. But. For what it worth I would never write code like this ( new XXX ) in the parameters section of the function. It just inherently feels wrong to me. I am also paranoid to the degree that I always put brackets in the expressions even when it is not really needed and do all kinds of other paranoid stuff.
- MichaelMoser123 5y agospeaking about shared_ptr, they have a reference count that is done as an atomic counter, because you could use the shared_ptr instance from multiple threads, so that it has to be as general as possible. Now that atomic counter was not needed in my case, as the objects were only accessed from the same thread; however it had some surprisingly adverse effects on performance, in my projects at least... i think they should add some template argument to determine if an atomic counter is used or not, exactly for the cases where the shared_ptr object is used exclusively from a single thread; but they didn't do that in the standard.
- MichaelMoser123 5y agoin gcc the shared_ptr is derived from __shared_ptr, where you can pass a lock policy trait that goes without locking. wow. But i am afraid that is implementation specific.
- skocznymroczny 5y agoThe animated distracting banner feels like more of a footgun to me.
- rom1v 5y agoMy favourite is: struct Dummy { Dummy(int) {} }; struct World { World(const Dummy &) {} void hello() {} }; int main() { int value = 42; World world(Dummy(value)); // fails to compile // World world(Dummy(42)); // works world.hello(); return 0; }
- dw-im-here 5y agoBravo Bjarne! You've done it again!
- slavik81 5y agoThis is known as "the most vexing parse". In 99.9% of cases, it's just a surprising compiler error message that you learn to avoid. However, there's a related version of this problem which can lead to accidentally declaring a function prototype rather than acquiring a lock. You'll get compiler warnings from -Wshadow, but the seriousness of the problem might not be obvious. That said, it's a very rare problem these days, due to the introduction of uniform initialization in C++11.
- rocqua 5y agoFor anyone wondering. The issue is that the line: World world(Dummy(value)); Can be interpreted as the following function declaration: World world(Dummy value); As mentioned in child comment. This is sometimes called the most vexing parse: https://en.wikipedia.org/wiki/Most_vexing_parse https://en.wikipedia.org/wiki/Most_vexing_parse It originates because C++ allows superfluous parentheses around function parameter declarations.
- PostThisTooFast 5y agoA "footgun?" No. Use real words. There are plenty of them.
- slavik81 5y agoI'm a big fan of Scott Meyer's Effective C++. It's a little dated now, but it was the most valuable book I'd ever read on the language. Louis Brandy's Curiously Recurring Bugs at Facebook presentation from CppCon17 has somewhat of the same feeling, though it only covers a few bugs: https://youtu.be/lkgszkPnV8g https://youtu.be/lkgszkPnV8g
- wink 5y ago> contributions to OpenMW What is OpenMW? click link. No info. Oh, FAQ. > "What is OpenMW?" "OpenMW is a free, open source, and modern engine which re-implements and extends the 2002 Gamebryo engine for the open-world role-playing game The Elder Scrolls III: Morrowind." Maybe, just maybe, that shouldn't be a FAQ but right on the main page.
- inglor_cz 5y agoSlightly offtopic, but the word "meaningful", present in the first sentence of the article, has seen a massive growth in use in last months. Suddenly I see it everywhere. Politics, economics, personal anecdotes, programming. Not just clothes can be fashionable; vocabulary, too.
- theandrewbailey 5y agoIt's a powerful word. Do those last months co-incide with you using HN more? I ask because that happened to me when I started using this site (~8 years ago). Other words and terms that I noticed more were "useful", "conformation bias", and "correlation isn't causation"; all linked back to me using HN more.
- benreesman 5y agoThe article is perfectly reasonable. But the comments make me wish HN had subreddits.