9 ms·
What =delete means
- SavantIdiot 5y agoI'm so done with C++. When a fundamental keyword becomes a semantic pitfall, you've created an esoteric niche for enthusiasts, not a useful tool.
- jcelerier 5y ago> I'm so done with C++. When a fundamental keyword becomes a semantic pitfall, you've created an esoteric niche for enthusiasts, not a useful tool. you think quux wouldn't be able to find semantic pitfalls in literally every language you would use instead ?
- tux3 5y agoSome language designs have more semantic pitfalls than others. All else equals, those would be preferable. C++ is an old beast with many many footguns. There's a more modern subset hiding inside, these days, but let's not pretend every language has the same pitfalls that C++ has.
- jcelerier 5y agosure, but there's also a deep culture in the C++ blogosphere to go and seek the deepest and darkest corners and exhibit them as it's a very fun puzzle game. the same people applied to Python, Java or LISP would yield endless articles on pitfalls of those
- tragomaskhalos 5y agoIn the early 90's there were two print magazines: "The C++ Report" and "The Smalltalk Report". The former, even with the far simpler language it was then, was chock full of programming arcana and 'what does this code do?' type puzzles. The latter, by contrast, had effectively zero such content. I loved both languages but this difference was always very stark.
- SanFranManDan 5y agoIf they are endless where are they?
- pjmlp 5y agoSearch for Java Puzzles books
- pjmlp 5y agoUntil one delves into all the cool niche features being added into Java, C#, F#, Python,...., even C. Unless we are talking about v1.0 there always such cases when a language is around long enough.
- edflsafoiewq 5y agoWhat is the semantic pitfall here?
- beached_whale 5y agoFor almost everyone, none. delete doesn’t remove the method from the overload set, it leaves it there in order to give the caller an error saying don’t do that.
- klyrs 5y agoIt also prevents the compiler from emitting a default implementation for the deleted method.
- tialaramex 5y agoC++ has a keyword, "delete" which originally refers to an operator that destroys objects, thus calling their destructor and giving back resources (most obviously memory) allocated for their lifetime. But, adding keywords to C++ is expensive. You can't use these as symbols, you can't name a class, a variable, a function or anything "delete" because that's a keyword and so it's reserved. A new keyword would clobber existing symbols, and that's painful, so, C++ tries not to do it, instead repurposing existing keywords. So as well as the operator named "delete" now "delete" refers to this feature where you can tell the compiler that this particular overload mustn't be used, if it was looking for an overload, it won't use this because you explicitly said not to (even if it could have otherwise conjured a default) and if somebody else called it by mistake now they get a compile error saying not to. I don't think they would naturally have written =delete if not for being conscious that doing so is "free" (the word is already reserved for something else) whereas some other word would have caused compatibility problems.
- edflsafoiewq 5y agoWhat, you think the syntax is funny? I guess, but that's not a semantic pitfall.
- enriquto 5y ago> I'm so done with C++. When a fundamental keyword becomes a semantic pitfall, you've created an esoteric niche for enthusiasts but it always was!
- codebolt 5y agoI'm with you. The only thing = delete means to me is that I'm happy C++ isn't part of my dayjob.
- mikepurvis 5y agoI think for most of us mere mortals, the only normal use for =delete is making a class non-copyable. And for that, my muscle memory is already wired to inheriting from boost::noncopyable anyway.
- jpm48 5y agoI put private : myclass(const &myclass )=delete; Just to be safe :-)
- ziml77 5y agoFunny thing there is that one could read that as saying that the copy constructor's deletion is private and therefore still accessible in the public interface. I wouldn't put it past C++ to do something as crazy as that.
- bialpio 5y agoIIRC this will make the compiler error less helpful than it could be? I think you'd get an "attempt to use private member" instead of "attempt to use deleted member". End result is probably the same, but it feels like you're not saying what you mean with the code. Edit: NVM, looks like all major compilers will say that the copy ctor is deleted. https://godbolt.org/z/jTd3714Tb https://godbolt.org/z/jTd3714Tb
- Psychlist 5y agoclang-tidy will ask that you put in the full set. Foo() = delete; Foo(const Foo& orig) = delete; Foo(Foo&& orig) = delete; Foo operator=(const Foo &other) = delete; Foo operator=(Foo &&other) = delete; (add const to taste)
- pansa2 5y ago> I'm so done with C++. But what to use instead? Especially in an industry like game engine development, where C++ is basically all there is (and almost all there’s ever been)? Are we forever going to be stuck with every company trying to reduce complexity by defining their own custom subset of C++?
- nynx 5y agoThe main alternative is likely rust.
- criddell 5y agoAre you saying that for game engine development, Rust is the second most popular option?
- SavantIdiot 5y agoI didn't say "You can't use it," I said "I" am done with it. Have fun! Write some cool games!
- pansa2 5y agoThanks for the encouragement, it’s appreciated.
- fullstop 5y agoSomeone is going to say Rust, and I might agree with them at some point in the future. I periodically check https://www.areweguiyet.com/ https://www.areweguiyet.com/ to see the state of things, but C++ is still king here. I cut my teeth on C++ but was then employed to write code in C. After almost two decades of doing this, C++ looks vastly different to what I remember from 2001 and kind of ugly to me. I'm sure, however, if I had stuck with C++ for the last twenty years it would feel like home.
- jerf 5y agoThe places where you must use C++ are a dwindling niche. Large niches in their own right, certainly, but niches. Once you leave those niches there is an explosion of possibilities. I'm coming up on year 25 of my career and I haven't touched C++ since school, if one can indeed call what is covered in school C++. Especially nowadays. And C and Java I've barely touched. I certainly couldn't put them on my resume with a straight face. I say this because you kind of sound like you're making some sort of plaintive plea, as if C++ is somehow the only viable option in the world and who could even dream of stepping outside of it? And I'm telling you that while that may be true in an ever-decreasing set of niches, it is not true in general anymore and hasn't been for a long time.
- carpenecopinum 5y agoIf a language feature being weird is enough to declare that you're "done with it", you won't have too many languages to work with in the end. Maybe some LISP, I guess? You don't become a good craftsman by rejecting every tool that isn't perfect. You become one by knowing your tools and their flaws and strengths well.
- SavantIdiot 5y ago> You become one by knowing your tools and their flaws and strengths well. Yes, that's why I said "I" am done with it, not "you should be done with it." There's no need for me to use it ever. Except when forced to with mbed, TFLiteMicro, and the occasional port of an Arduino driver to C. I've been at this since before C++ existed. I've watched it come in to the world, and I've watched it mutate, Akira-like, into an academic omphaloskepsis. EDIT: Fun story: I learned C++ in ... 1990? ... by watching a series of videos on VHS tape taught by none other than Bjarne Stroustrup himself. I think it was a bonus that came with the purchase of the first version of the Borland C++ compiler for OS/2.
- simias 5y agoI must say that I'm always a bit in awe when I read modern C++ and I realize that I barely understand what's going on even though ~10 years ago I considered that it was the language I knew best. And even back then it was already a sprawling monster of a language. Nowadays the idea of having to maintain a large C++ codebase scares me. Too many footguns and arcane knowledge required.
- kllrnohj 5y agoEh? '=delete' is a bad example of "footgun" or "arcane knowledge". There are those in C++, sure, but this isn't one of them. You can happily never know the existence of '=delete' and nothing about your code changes. And if you ever hit a libraries usage of it, like the standard library, you get a pretty clear error message at compile time instead of an actual footgun in C++98 like memory corruption or runtime crashes. '=delete' is basically the entire reason why std::unique_ptr is safe and std::auto_ptr is a footgun. It reduces the ammo aimed at yourself & the amount of knowledge you need to know (like the knowledge to never put auto_ptr in a vector)
- simias 5y agoI was talking generally, not for this particular feature. But it would still be sort of arcane knowledge for me since when I last actively used C++ `=delete` either didn't exist or was not in common use, so if I encountered it in some codebase I'd probably guess what it does but still have no idea about the implications. Like, are there other =<something> construct? Is it overridable or overloadable by the user? Can I use it to "erase" any member of a class, for instance to hide a parent member from an inherited class? I suspect that the answer to all of these questions is "no", but I can't know for sure without deep diving into some C++ ref. In the C++ I knew there was nothing resembling this syntax, and `delete` was only the keyword you used to free memory.
- cesarb 5y ago> Like, are there other =<something> construct? Yes, there's "= 0" to mark a virtual method as not implemented in this class (that is, it must be implemented by a subclass), which is older than "= delete". Conceptually, it sets the corresponding slot in the virtual method table to null instead of a pointer to the (non-existent) method, except that it actually doesn't do that, it sets that slot to a pointer to a "pure virtual method called" function from the standard library, which AFAIK prints an error message and exits the program (IIRC, this is because there are some situations in which you can actually manage to call such a pure virtual method, like calling it from a function called within the constructor or destructor of the base class.)
- gpderetta 5y agoThere is no semantic pitfall in = delete. = default on the other hand...
- kccqzy 5y agoHow is it a pitfall? The article clearly elucidates several uses of the "=delete" construct. I don't see any pitfalls, just some new uses of the feature. And I expect most people to be the same: most people only ever use "=delete" on the copy constructor and the copy assignment operator, now this article tells them you can actually use it on other things too. There's no pit to fall into, just new ways to use a feature.
- agent327 5y agoIt's just a piece of programming knowledge being explained. It's very far from a 'semantic pitfall' or an 'esoteric niche'. Don't be such a drama queen.
- cletus 5y agoIt's well known that no one really programs in C++. They program in whatever subset of C++ their organization allows, their brain can handle or both. Personally I found Google's C++ dialect to be sane, even pleasant. No exceptions, no mutable reference parameters (side note: this was a giant language fail that foo(f) could be a const reference or a non-const reference and there's no way to know without looking at the declaration), pervasive use of union types (absl::Status/StatusOr are the open source versions) and, here's the big one, individual teams were expressly forbidden from creating their own templates. Now compare this to Facebook's dialect: exceptions allowed, mutable reference parameters allowed (side note: people weren't strict with const-ifying reference parameters so you actually didn't know if something was actually mutated or not), functions that routinely just return bool (so helpful) and you can create your own templates. But seeing this post makes me see the wisdom in not only how cut down Google's dialect is but also that stopping teams creating their own templates is the only sane choice. The depth of knowledge required to create templates that don't behave unexpectedly (eg dangling references, redundant copying, useable with move semantics, etc) is so large that only specialists should engage in it. There is a certain breed of programmer who will use a feature of a language because it's there. They will view esoteric features, unnecessary complexity and brevity over readability as not only virtues but goals with which they can tell the world how smart they are. If you write code for you, you're either doing it alone or you're not a team player. You write code for the next person who comes along and has to figure out why it's broken or just how it works, not to be as clever as you would like to think you are.
- ruohola 5y ago> functions that routinely just return bool (so helpful) I don't get it? What's wrong with returning a bool?
- cletus 5y agoThis applies to function parameters and return values: you almost never want to use a bool. Instead you want to use an enum with two values. Booleans are hard to read in most cases. Obviously there are trivial cases where this isn't the case (eg bool isDigit(char) is completely fine). Contrived example: bool connectToHost(string hostname, bool useSsl); First problem: if it fails, why does it fail? Some will be tempted to throw an exception. Better is to return some kind of status. Second problem: you add another version of SSL, now what? If you'd used an enum, it's just another value. If not, you now need to retrofit it. Better version: absl::Status connect(string hostname, EncryptionType encType); People will often make mistakes when a function has 3 or more booleans and put the wrong value in the wrong parameter. With strongly typed arguments, this becomes a compiler error. People will extend booleans to add a third value. In Java, for example: Optional<Boolean> foo But it doesn't end there. As I like to say, for when three values for your boolean just aren't enough: @nullable Optional<Boolean> foo Just start with enums.
- dataflow 5y agoIt's never been necessary to use delete to make a class uncopyable. It was always possible by just declaring (but not defining) a private copy constructor/assignment. I'd still do the same thing honestly, it's fewer keystrokes and not pointlessly backwards-incompatible. Better yet, for the majority of cases, just inherit from an uncopyable class like boost::noncopyable.
- kllrnohj 5y agoIf you declare but don't define a private copy constructor/assignment then you hit vague linker errors elsewhere that will likely send a user on a chase trying to figure out how their include paths don't match their linker paths and which library they forgot to link against. '= delete' makes it exceedingly clear that what they are doing is not allowed, rather than "oh god dammit cmake what did I miss now..." Since '= deleted' was added in C++11, there's really not any good "backwards-incompatible" arguments to be made about avoiding it. C++11 support is extremely broad at this point and has been for many, many years now.
- dataflow 5y ago> If you declare but don't define a private copy constructor/assignment then you hit vague linker errors elsewhere that will likely send a user on a chase trying to figure out how their include paths don't match their linker paths and which library they forgot to link against. I think you missed the importance of private. Users of it won't get it to compile for them to get a linker error.
- jcranmer 5y agoA private copy constructor can still be copied in the class itself. If you omit the definition, you still get a linker error message, but linker errors are among the most obtuse to actually discover. (Where did the copy construction actually happen? Who knows! You get, at best, the function that called it). A deleted copy constructor produces better error messages. And it's not really backwards-incompatible at this point--deleted functions exist in compiler versions old enough to get a COVID-19 vaccine.
- cogman10 5y agoSo I read the article, and maybe I'm thick... but what does `=delete` mean? I saw a bunch of examples about how it will trigger errors with l/rvalues in some scenario, but I'm really no clear on the meaning of it. Would someone mind explaining the meaning? Is it some sort of lifetime opt-in thing? Is it restricting how a method can be called? What's going on here? What is `=delete` telling the compiler?
- pjmlp 5y agoA very basic and quite high level explanation is as follows. In several cases the C++ compiler will generate default implementation for specific methods. However there are cases where that isn't desirable, and until =delete came to be, the workaround was to mark the method as private without implementation. So =delete deals away with such hack, although as mentioned this is a superficial overview of its purpose.
- cogman10 5y agoOk, that's the C++ I learned many moons back (C++98/03). And it makes sense why that exists. Thanks.
- TFortunato 5y agoYou're definitely not thick! This is getting a bit into the weeds of lower-level C++, but it is useful. So what delete is doing is explicitly saying that a given method (with a particular signature) is defined to not exist. It's usually used in cases where the compiler would automatically create a method for you, or use a method you wouldn't want to be used. The example they give is the reference wrapper, which (as the name might suggest), is used to wrap a reference to some thing. To reiterate, with hopefully a bit more of what is going on. If the creator of this method had just created a function: template<class T> auto cref(const T&) -> std::reference_wrapper<const T>; Then by C++ overloading rules, you could call this function with either an const ref LValue, or an RValue of type T. (In their example, they used a number). Which for 95% of functions is totally fine, and desired behavior! However, in this case, it would be bad, because remember, we are trying to wrap a reference to some value (e.g. basically a pointer under the hood), so a pointer to some ephemeral value is likely not what we want. In order to solve this, the creator explicitly adds: template<class T> auto cref(const T&&) = delete; Now, if the user calls cref on an RValue like a number, they will get a nice error message saying that the function has been explicitly deleted. The reason this works is because "const T&&" is the better match for the type of an RValue, compared to "const T&", so this is the overload that the compiler will try to use, rather than the original version above. Some other reasons to use delete, is if you want to do stuff like explicitly forbid the use of copy constructors, because you have some object that you don't want copies made of for whatever reason. By explicitly deleting the copy constructor, you can be sure that no copies are accidentally made somewhere in user code (which is especially useful when your code interacts with other libraries you don't control) I hope that made sense, but the TLDR is that there are a lot of ways construct objects, delete objects, to copy / move data around, etc. If you are doing low-level memory management / optimization, you may want to explicitly tell the compiler not to do the normal "helpful" stuff it does for you, such as creating default constructors / overloads, and this is the supported way of doing that in the standard.
- iulian_r 5y agoHow do you handle failures in constructors without exceptions?
- ginko 5y agoIn my company we do so by disallowing constructors to fail. If an object needs to be initialized with the potential of failure you need to call an init() function that returns an error code after construction. Yes, that makes RAII basically impossible.
- ahartmetz 5y agoIMO the most important part of RAII is really the other side, "destruction is resource divestment" - and that still works. That is the main purpose of lock guards, refcounting wrappers, file objects and so on.
- kllrnohj 5y agoWhy not a factory function that returns std::optional<T> instead? Or better a variant of T or error code? The construct-then-init pattern is so annoying to deal with.
- klyrs 5y agoThe safest & fastest way I'm aware of to use a unique_ptr factory. It involves adding an error flag to the class; the factory checks the error flag and resets the unique_ptr if it's true.
- nyanpasu64 5y agoC++ constructors cannot express fallibility. Rust factory functions cannot placement-initialize (write into a pointer) an object too big to fit on the stack (aside from the perma-unstable `box` syntax, which I don't know if it even works or not). A unique_ptr factory cannot stack-allocate an object. I don't know if it's possible to create a safe interface to fallible initialization, which is agnostic to whether the object will be constructed via return onto the stack, or onto heap memory. I'm interested to hear about proposals though (I've discussed this in the Rust community discord, but that isn't as public or concrete as a long-form article).
- butterisgood 5y agoYes, it's a good idea to know the implicit rules for constructors and assignment operators in C++. No, it's not a bad idea to be as explicit as possible all the time when writing code, because code is for humans first, and computers second. I always found =delete to be very nice documentation of what I can expect of a struct, class etc in terms of valid uses. And C++ is huge - assuming all the people on your team understand all of it, and the corners and implicit behaviors is really not a great idea. So you should remove any potential source of confusion, or ambiguity in a source tree - as much as possible.
- bendbro 5y agoI haven't seen this syntax before and I just knew it would be c++.
- admax88qqq 5y agoThe longer I've been away from C++ the happier I've been.