Managed Wrappers and Hidden Interdependencies
C++ c++ managed c++
Published: 2007-01-10
Managed Wrappers and Hidden Interdependencies

Let’s say you have the following unmanaged code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#pragma unmanaged

class Stream { ... }; // Conceptual stream class

class StreamWriter
{
public:
    StreamWriter(Stream* pStream) : m_pStream(pStream) {}
    ~StreamWriter() { /* Use m_pStream in some way */ }

    ...

private:
    Stream* m_pStream;
};

void f()
{
    Stream stream;
    StreamWriter streamWriter(&stream);

    // Use streamWriter
    // streamWriter is destroyed
    // stream is destroyed
}

Note that StreamWriter’s destructor uses m_pStream (perhaps by flushing the stream). This means that the order of destruction is important — StreamWriter must be destroyed before its underlying Stream is.

Now let’s try to write and use some simple managed C++ wrappers for these classes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#pragma managed

public __gc class ManagedStream
{
public:
    ManagedStream() : m_pStream(new Stream) {}

    // NOTE: This is a finalizer, not a determinstic destructor
    ~ManagedStream() { delete m_pStream; }

public private: // Make accessible by ManagedStreamWriter
    Stream __nogc* m_pStream;
};

public __gc class ManagedStreamWriter
{
public:
    ManagedStreamWriter(ManagedStream* pStream) :
        m_pStreamWriter(new StreamWriter(pStream->m_pStream)) {}

    // NOTE: This is a finalizer, not a determinstic destructor
    ~ManagedStreamWriter() { delete m_pStreamWriter; }

private:
    StreamWriter __nogc* m_pStreamWriter;
};

void f()
{
    ManagedStream stream = __gc new ManagedStream();
    ManagedStreamWriter streamWriter = __gc new ManagedStreamWriter(stream);

    // Use streamWriter
    // GC will clean up stream and streamWriter
}

See the problem?

As I (gratituously) hinted above, we have a problem due to nondeterminstic destruction. Since the GC does not define the order in which it will destroy managed objects, we cannot guarantee that the ManagedStreamWriter will be destroyed before the ManagedStream. If the ManagedStream is destroyed first, then its Stream will be deleted before the ManagedStreamWriter’s StreamWriter destructor is called. This means that StreamWriter will be using a deleted pointer — a sure recipe for disaster.

I can think of a few possible solutions to this problem:

  1. Have the managed classes implement IDisposable, and require developers to use it to achieve determinstic destruction. The main downside to this approach is “what if developers forget?”
  2. Recapture the interdependencies among unmanaged classes in the managed wrappers. For example, add a reference in ManagedStreamWriter to the ManagedStream object. This will force the GC to properly order their destruction, and is probably the right way to go.