auto_ptr or shared_ptr equivalent in managed C++/CLI classes

孤街醉人 提交于 2019-12-05 02:06:17

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!