8 ms·
Rule of Zero (C++)
- jamesaguilar 14y agoI like that using technique, but why is it using and not typedef? I thought using was meant for exposing names from superclasses.
- yannickt 14y agoIn the OP example, "using" has the same semantics as "typedef". The new syntax emerged from the need for "template typedefs". http://www.stroustrup.com/C++11FAQ.html#template-alias http://www.stroustrup.com/C++11FAQ.html#template-alias
- jamesaguilar 14y agoOh. I wish they would have just shoehorned it into typedef somehow. I guess they must have had reasons why they couldn't.
- pmr_ 14y agoThe alias syntax has the benefit of not requiring typename everywhere because the syntax requires the right parts to be types and doesn't allow for ambiguities as does typedef. This makes code in dependent contexts a lot easier to read and to write.
- snogglethorpe 14y ago+1 on that; people intuitively expect template'd typedefs to work until they discover they don't. Oh well. You can read about the reasoning behind the new syntax here: http://www.emarcus.org/papers/n1449.pdf http://www.emarcus.org/papers/n1449.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1489.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n148...
- Sharlin 14y agoIn C++11 you can write "typedef templates". However, as "typedef" has always been a misleading keyword (it does not define a new type, it declares an alias for an existing type) it was decided to instead overload the using keyword: template <typename T> using MyVector = std::vector<T, MyAlloc>; As a side effect, it is now also possible to use using as a 1:1 replacement for typedef: // strictly equivalent to typedef int MyInt; using MyInt = int;
- AlexandrB 14y agoAfter reading the C++ FAQ on this I can accept that using tyepdef may have been impossible/confusing, but why overload "using"? This is one of the things that makes C++ mega-complicated. The same keywords have different meanings based on context, when really a new keyword should just have been used. For example "virtual" functions vs "virtual" inheritance.
- skrebbel 14y agoThe moment you add a keyword to a popular language, you break lots of existing code that happen to have that keyword as an identifier, e.g. as a variable, class or function. This means that when adding features that need a new keyword, you best overload an existing one. It's for this reason, too, that Java 7 overloaded `try` to implement some sort of poor-man's-RAII-support, instead of adding a new keyword (such as C#'s `using`, which does the same, and was by the way also overloaded for the same reason)
- shin_lao 14y agoIt's nice to see more and more C++ articles. Some additions: - The least you allocate on the heap, the better. Move semantics really help in that aspect; - Smart pointers are not magic. Although I really think using unique_ptr whenever possible is a good idea, shared_ptr comes with a performance cost (especially in multithreaded environments), can introduce vicious memory leaks and is often used as an excuse to not think your lifetime cycle through.
- pjmlp 14y agoI also like it. C++ suffered for a long time due to lack of quality libraries. This now seems to be finally changing, at least until another language is a good enough replacement for it. I am keeping an eye how D and Rust evolve, additionally Ada seems to be getting some users, at least here in Europe.
- mhd 14y agoAda in Europe? Interesting, where did you encounter that? As for quality libraries, I'd almost say that we had too much of them. For every platform and every different C++ methodology/subset (from "C with Classes, ocassionally Structs" to "Post-Modern Template Abuse") had its own set of supporting libraries. Often good enough, but most of the time not the ideal source for your particular project, and very hard to integrate, if every code paragraph follows a different paradigm, depending on what library your calling. Still don't see a good solution to that. Quite likely that your GUI library won't quite mesh with your collections, data parsing or network support.
- pjmlp 14y ago> Ada in Europe? Interesting, where did you encounter that? I heard it at this year FOSDEM. Since GNAT availability many universities seem to be making use of it. As for the industry I guess it still constrained to the usual types of systems where Human life is very important. As for the libraries you're doomed to have that for all libraries that are not part of the standard library. Even the "comes with batteries" languages suffer from this when you need to integrate external libraries. If Java and .NET didn't happen, maybe there would already be an InteliJ for C++. I am looking forward for the tooling progresses made possible by using the compiler as plugins, as clang shows.
- rwmj 14y agoDo people who write C++ also manually allocate disk blocks instead of using the filesystem? Just use a garbage collector. These problems will all go away.
- Patient0 14y agoThe problems start when you need to manage resources other than memory. Examples of things that require explicit clean up: -> Files -> Sockets -> Transactions The C++ resource model can be applied to all resources, not just memory. Garbage collection only "solves" memory management for you - often that's the least important resource that your program is managing.
- pjmlp 14y agoTrue, however you have mechanisms like using, with, try, scope, defer that GC enabled languages offer. C++ destructors benefit is that you don't forget to call such constructs.
- strictfp 14y agoMost (all?) of these cannot cope with trees of objects, plus that they leave the responsibility of destructing to the user of the object. So they are just as ugly as external locking. Problem is that very few people understand this, so they implement "using" and feel content. I would give an arm and a leg for RAII on the JVM.
- pjmlp 14y ago> Most (all?) of these cannot cope with trees of objects You can if all "destructors" take care of also closing the internal resources, thus initiating a cascade process of the object owned by them. But you're right, this leaves the responsibility in the user's side. > I would give an arm and a leg for RAII on the JVM. At least they finally added the "using" concept. In a few more versions maybe they get to add values.
- fauigerzigerk 14y ago
- huhtenberg 14y agoAbstracting the ownership behind an interface presumably is needed when the ownership model is very complex. From my experience this is nothing but a big red flag. If you need a class to manage an ownership, it means that you can't easily trace its movement, in which case it means that it is a total bitch to debug, leave alone being able to read through the code and understand where that damn ownership is at any given moment. I know it's beautiful language with a laundry list of features, but keeping things simple is still the best approach: #define __no_copying(type) \ \ private: \ type(const type &); \ type & operator = (const type &); \ public: class foo { public: foo(); __no_copying(foo); ... } In a spaghetti-less code this typically applies in 99% of all cases. There's a remaining 1%, which it's easier and cleaner to handle on a case by case basis.
- gregsq 14y agoAgree in the main. Even before smart_ptr's were integrated into the standard, bespoke versions that appeared to some to remove scoping confusion had a tendency to propagate like weeds. In the majority of cases, const correctness, mutability if needed and good scoping concepts removed redundant reference counting run time garbage. On one project I worked on as a contractor, and quite a large one at that, I removed every single one of them and rescoped the code base. It took a while but performance alone improved by about 400%
- rmartinho 14y agoI'll say this just once: smart pointers and reference counting are not the same thing, and neither of them implies the other.
- gregsq 14y agoDidn't need to say it at all. I probably wasn't being clear enough but I was referring to early versions that were called smart precisely because they removed the need for the programmer to count because they counted themselves. Hence 'smart'. Before boost and others cleaned it all up. As others are pointing out they have advantages and disadvantages. It all depends on the situation. But they're certainly not free because they have a scope cost. Code size and simplifying compiler optimisation are important too. I think it's worth that pointing out.
- ambrop7 14y agoTo me, "Rule of Zero" sounds more like not implementing {con,copy-con,de}structors, i.e. forgoing RAII. I've been doing this quite a lot, and it makes writing low-level and optimized code so easier. Actually, I find that having fixed ownership makes much more sense than reference counting for the majority of cases. Example: we have a FileSystem, and a bunch of File's belonging to this FileSystem. Whenever a part of a program needs a file, it just initializes its own File object, and when it doesn't need it anymore, it releases it somehow (e.g. file.deinit() or destructor if RAII is used). Even if two users both need the same file, each gets its own File. The FileSystem internal implementation can take care of any resources sharing, invisible to the users. As far as the memory management of FileSystem is concerned: again, in most cases, you don't need shared_ptr<FileSystem>. Just make sure the FileSystem stays alive as long as there's the possibility that anyone is using it. Like initialize it at the beginning of the program, and deinitialize it during shutdown at the right point.
- mpyne 14y agoThis "Rule of Zero" construct doesn't forgo RAII, since RAII does not simply mean "write constructors and destructors". Instead it allows the compiler and language to automatically do the right thing to enable RAII by using appropriate library-provided building blocks. E.g. his std::unique_ptr + custom deleter type enables the compiler to automatically make a RAII-compliant class for the author, so it's still RAII, just automatically implemented (except for the ctor, in this case).
- radarsat1 14y agoThe codebase I'm currently working on has quite a few bugs related to ownership. However, the programmers I'm working with are very capable and all are familiar with different kinds of smart pointers in the STL. Unfortunately they are either, 1) typedef'd to the point where it's hard to tell what kind of ownership is used where, 2) often can't be used because objects need to be passed by reference to libraries that use regular-old-pointers. I think many bugs could have been avoided by not typedef'ing our pointers, because when you have to type `std::shared_ptr<myclass>`, then you know what kind of pointer it is. On the other hand, if you have to, at least call the typedef `myclassSharedPtr` instead of `myclassPtr`. But for (2), I don't see a work-around. How can you write good code when your critical dependencies don't play nice?
- rmartinho 14y ago> often can't be used because objects need to be passed by reference to libraries that use regular-old-pointers. I don't understand what you mean by this. If you have a `smart_ptr<T> p;` nothing prevents you from passing `*p` or `p.get()` to some legacy interface. You only have trouble if that legacy interface wants to claim ownership of the object.
- ben0x539 14y agoI think the issue is that the typedef is intended to hide the smartptrness so it's not obvious what the API for getting an old-style pointer is, or whether getting an old-style pointer is even part of the intended public interface anymore (beyond p.operator->() anyway ;)
- radarsat1 14y ago> You only have trouble if that legacy interface wants to claim ownership of the object. That's exactly what I mean. This happens. My point is just that even the best intentions are easily subverted in a real-world scenario where you didn't write the whole codebase yourself from scratch.
- br1 14y agoI agree on (1). Typedef obscures more than it helps. On (2), I think the solution is intrusiveness. intrusive data structures and intrusive_ptr should be used more in C++. The dislike for intrusiveness is rooted on equating classes with responsibilities. A single responsibility is often spread over several classes, because the classes form a useful cluster. A clear case is items of a collection. If an object already knows it's an item in a collection, there's really no harm in using intrusive lists.
- andrewcooke 14y agocache http://webcache.googleusercontent.com/search?q=cache:8r4wIEjdtwYJ:rmartinho.github.com/2012/08/15/rule-of-zero.html+Rule+of+Zero&cd=1&hl=en&ct=clnk&gl=cl http://webcache.googleusercontent.com/search?q=cache:8r4wIEj...
- Strilanc 14y agoThere's a similar rule of thumb in .Net with respect to managing native resources. Inlining the logic that handles the lifetime is much more bug prone than encapsulating that logic into a wrapper class (e.g. SafeHandle http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx http://msdn.microsoft.com/en-us/library/system.runtime.inter... does this).
- Flow 14y agoI guess I'm lucky enough to never have seen that class in code I've seen. :) That seems like typical Microsoft object-orientation. It's not really much of encapsulation. Reminds me of MFC :-/
- pjmlp 14y agoActually Microsoft started by developing a C++ library with lots of OO in the design. However not everything went as they expected and people were also demanding something more light over Win16 and MFC was born. http://computer-programming-forum.com/82-mfc/d13ea80282846f9f.htm http://computer-programming-forum.com/82-mfc/d13ea80282846f9...
- davvid 14y agoNice article, but the use of std::wstring threw me in a little loop. Perhaps the author is on Windows where its usage is more common?
- spoondan 14y agoPer the article, "As an example, let’s write a class that owns a HMODULE resource from the Windows API."