auto_ptr or shared_ptr equivalent in managed C++/CLI classes
Asked Answered
G

4

10

In C++/CLI , you can use native types in a managed class by it is not allowed to hold a member of a native class in a managed class : you need to use pointers in that case.

Here is an example :

class NativeClass
{
....
};


public ref class ManagedClass
{
private:
  NativeClass mNativeClass; // Not allowed !

  NativeClass * mNativeClass; // OK

  auto_ptr<NativeClass> mNativeClass; //Not allowed !
  boost::shared_ptr<NativeClass> mNativeClass; //Not allowed !

};

Does anyone know of an equivalent of shared_ptr in the C++/CLI world?

Edit: Thanks for your suggestion, "1800-Information". Following your suggestion, I checked about STL.Net but it is only available with Visual Studio 2008, and it provides containers + algorithms, but no smart pointers.

Gauzy answered 6/10, 2008 at 22:6 Comment(1)
codereview.stackexchange.com/questions/1695/…Fishtail
G
2

I found the answer on codeproject :

Nishant Sivakumar posted an article about this at http://www.codeproject.com/KB/mcpp/CAutoNativePtr.aspx

On this page, also look for the comment by Denis N. Shevchenko : he provides a stl-like implementation that works quite well.

Gauzy answered 6/10, 2008 at 23:26 Comment(1)
please avoid links, they could get brokenSpiral
L
2

I haven't thoroughly tested this but how about something like the following:

#pragma once

#include <memory>

template <class T>
public ref class m_shared_ptr sealed
{
    std::shared_ptr<T>* pPtr;

public:
    m_shared_ptr() 
        : pPtr(nullptr) 
    {}

    m_shared_ptr(T* t) {
        pPtr = new std::shared_ptr<T>(t);
    }

    m_shared_ptr(std::shared_ptr<T> t) {
        pPtr = new std::shared_ptr<T>(t);
    }

    m_shared_ptr(const m_shared_ptr<T>% t) {
        pPtr = new std::shared_ptr<T>(*t.pPtr);
    }

    !m_shared_ptr() {
        delete pPtr;
    }

    ~m_shared_ptr() {
    delete pPtr;
    }

    operator std::shared_ptr<T>() {
        return *pPtr;
    }

    m_shared_ptr<T>% operator=(T* ptr) {
        pPtr = new std::shared_ptr<T>(ptr);
        return *this;
    }

    T* operator->() {
        return (*pPtr).get();
    }
};

This should let you use C++11/Boost's shared_ptrs interchangebly in ref classes.

Laszlo answered 28/9, 2012 at 16:35 Comment(0)
S
0

STL.Net is documented here. I don't know what state it is in or what use it might be for you.

Suttee answered 6/10, 2008 at 22:24 Comment(0)
W
0

For those who come here and looking for a managed auto_ptr:

#include <msclr/auto_gcroot.h>

...
{
  msclr::auto_gcroot<ManagedType^> item(gcnew ManagedType());
  ...
}

https://learn.microsoft.com/en-us/cpp/dotnet/auto-gcroot-class

Wed answered 7/4, 2022 at 14:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.