Repeated destructor calls and tracking handles in C++/CLI

前端 未结 2 782
醉酒成梦
醉酒成梦 2020-12-09 17:35

I\'m playing around with C++/CLI, using the MSDN documentation and the ECMA standard, and Visual C++ Express 2010. What struck me was the following departure from C++:

2条回答
  •  孤街浪徒
    2020-12-09 17:58

    Guidelines from standard C++ still apply:

    1. Calling delete on an automatic variable, or one that's already been cleaned up, is still a bad idea.

    2. It's a tracking pointer to a disposed object. Dereferencing such is a bad idea. With garbage collection, the memory is kept around as long as any non-weak reference exists, so you can't access the wrong object by accident, but you still can't use this disposed object in any useful way, since its invariants probably no longer hold.

    3. Multiple destruction can only happen on managed objects when your code is written in really bad style that would have been UB in standard C++ (see 1 above and 4 below).

    4. Explicitly calling the destructor on an automatic variable, then not creating a new one in its place for the automatic destruction call to find, is still a bad idea.

    In general, you think think of object lifetime as separate from memory allocation (just like standard C++ does). Garbage collection is used to manage deallocation -- so the memory is still there -- but the object is dead. Unlike standard C++, you can't go and reuse that memory for raw byte storage, because parts of the .NET runtime may assume the metadata is still valid.

    Neither the garbage collector nor "stack semantics" (automatic variable syntax) use reference counting.

    (Ugly details: disposing an object doesn't break the .NET runtime's own invariants concerning that object, so you can probably even still use it as a threading monitor. But that just makes an ugly hard-to-understand design, so please don't.)

提交回复
热议问题