7 ms·
C++ and Rust need destructors because they both have unwinding and thus need to know how to destroy things. If there is no unwinding then calling destructors ma
by jetzzz 8y ago
C++ and Rust need destructors because they both have unwinding and thus need to know how to destroy things. If there is no unwinding then calling destructors manually is not that bad if compiler checks that you do it. That said, I haven't used zig and don't know how it actually works.
- ioddly 8y agoI have yet to use Zig seriously, but I'm pretty sure "defer" is its solution to this problem: https://ziglang.org/documentation/master/#defer https://ziglang.org/documentation/master/#defer
- edflsafoiewq 8y agoI asked this in another thread, but how do generics work in the absence of destructors? Let's separate the idea of a destructor from the idea that a destructor is implicitly called at the end of a scope. In C++, if there weren't automatic destructor calls, you could still clean things up manually with a pseudo-destructor call, x.~T(), where T is the type of x. In C, there are no (user-defined) generics, so you always know the concrete type of x, so you know whether it needs to have a destructor called and what the name of that destructor is. In Zig, how would generic code create an instance of a generic type T that may or may not need to have a destructor called, ie. how do you know if you need to use defer and what the deferred expression should be? How would tooling be able to check that destructors were called if there is no special way of marking that a destructor exists?
- isaachier 8y agoHaving used Zig a bit, and C++ for years, I personally believe that this sort of scenario is pretty rare. You can always add a no-op dealloc method to your type if you want a generic function to handle it correctly. Moreover, Zig has awesome metaprogramming support so you can probably think of a way to check the type parameter for a dealloc method and only generate the dealloc call for those types.
- edflsafoiewq 8y agoPretty rare? What about ArrayList? I want ArrayList(T) to work whether T = i32 or T = ArrayList(i32). > You can always add a no-op dealloc method to your type if you want a generic function to handle it correctly You're looking at it from the perspective of the generic consumer, not the generic author. The generic author generally does not have the ability to edit the type. Plus there are many types that do not have methods at all (integers, points, etc.). > Moreover, Zig has awesome metaprogramming support so you can probably think of a way to check the type parameter for a dealloc method and only generate the dealloc call for those types. Yes, you can detect and call a method called deinit that has the appropriate signature using @reflect. You can even put this in a function and call it a pseudo-destructor. But there's no guarantee that deinit has the actual semantics of a destructor without some kind of language-level agreement between class authors.
- AndyKelley 8y ago> I want ArrayList(T) to work whether T = i32 or T = ArrayList(i32). This will work fine. Do you have a more specific example?
- edflsafoiewq 8y agoWhen I call deinit on an ArrayList(ArrayList(i32)) do the elements have deinit called on them?
- AndyKelley 8y agoHow are you expecting to call deinit on an i32?
- edflsafoiewq 8y agoNot sure what you mean. The elements of an ArrayList(ArrayList(i32)) are ArrayList(i32)s. To answer my question, no, they're not deinited. All deinit does is call self.allocator.free on the slice of elements, and for many allocators that's a nop. In fact none of ArrayLists methods take any kind of ownership of its elements. If you shrink an ArrayList(ArrayList(i32)) by one you leak the last ArrayList(i32). None of the methods call destructors on the elements because there is no generic notion of a destructor, only particular ad-hoc ones like deinit methods. ArrayList appears to solve the problem I mentioned above about generics not knowing if a generic type needs to have a destructor called by only supporting types that don't. In C++, you'd write the function that clears a vector something like void clear() { for (auto p = ptr; p != ptr + len; ++p) { p->~T(); } len = 0; } For a vector<vector<int>> the syntax p->~T() calls the destructor on a vector<int> element. While for an vector<int> the syntax p->~T() is a pseudo-destructor call, ie. it does nothing. This makes the same generic code work when the elements of a vector need to have a destructor called and when they don't.
- thechao 8y ago> In C, there are no (user-defined) generics C has had generics since C11. I’ve got a clone of “the good parts” of the std C++ template library (vector, unordered_map, ...) laying around somewhere.
- RhysU 8y agoPlease do share.
- isaachier 8y agoI imagine this is about tgmath.h. I've found the use of the word generic a bit misleading there.
- cygx 8y agoNo, it's very likely about _Generic. <tgmath.h> was added to C99 in an attempt to steal Fortran mindshare, ie making numerics and scientific computing less cumbersome (the same is true for other features, eg complex numbers or restrict). But in C99, it was still special-cased. The next standard C11 introduced _Generic so people could create their own type-generic interfaces.
- thechao 8y agoAs, below, there's a new statement: '_Generic()'. The expression looks like this: _Generic(x, type : value, ..., [default : value]) For a list of unique types, with an optional 'default' for any unrecognized type. You usually wrap the call to '_Generic' in a macro. For instance: #define vec_push_back(vec, val) \ _Generic(&vec, \ vecint : vecint_push_back, \ vecdbl : vecdbl_push_back, \ default : assert_vwrap)(&vec, val) Assuming that types 'vecint' and 'vecdbl' have been defined by the user. This does single-parameter parametric type dispatch. There's way to allow the user to use table-driven macros ('X-macros') to allow per-translation-unit definition of an arbitrary number of instantiations. The nice part, over C++, is that the generic instantiation is localized to a single translation-unit file, so you don't have to yell at the junior devs for instantiating templates without using an 'extern' construct.
- comex 8y agoIf the compiler checks that you do it, sure. For local variables, I'd say `defer` is an okay but not great substitute. If you call malloc() yourself, then sure, it's not hard to remember to stick a "defer { free(ptr); }" afterwards. But what if you call a function that returns an owned value? Can you tell just from looking at it that you're meant to free the thing afterward? CoreFoundation, a C library on Apple platforms, has a cute solution to this: a strict naming convention. [1] If a function returns a value at "+1" reference count, i.e. you have to release it yourself, the function's name should include "Create" or "Copy", even where that would otherwise seem unnatural. For example, "CFSocketCopyAddress" returns a socket's address as a CFDataRef, returned at +1. You might expect it to be called "CFSocketGetAddress", but "Get" is reserved for functions that return values at +0. As I said, cute – but fundamentally a workaround for language limitations. Distinguishing between two kinds of functions is exactly the sort of menial bookkeeping that computers excel at, whereas humans are prone to making mistakes. And – while CoreFoundation is forever stuck with the goal of C compatibility, Objective-C, which used to rely on a very similar system of manual retain/release and naming conventions, did ultimately transition to automatic reference counting. But it doesn't have to be automatic. One use for destructors is to automatically release locks, and an interesting alternative design for that exists in Clang's "thread safety" annotations. These are annotations you can add to existing C or C++ code that uses mutexes; their main purpose is to catch you if you access a variable protected by a mutex without owning the mutex, but they can also complain if you lock something and forgot to unlock it. You can annotate functions as "requires mutex" (i.e. you must call it with the mutex locked, and it stays locked after the function), "acquire" (call with it unlocked, returns with it locked), "release" (the opposite), and so on. I think I once tried to abuse the annotation system to enforce reference counting, but it was broken. But I'd love to see a more thorough and robust design along these lines. [1] https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-103029 https://developer.apple.com/library/archive/documentation/Co...