在C ++ / CLI中,您可以在托管类中使用本机类型,因为它不允许在托管类中保存本机类的成员:在这种情况下您需要使用指针。

以下是一个例子:

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 !

};

有没有人知道C ++ / CLI世界中的shared_ptr等价物?

编辑: 感谢您的建议,“1800-Information”。根据你的建议,我检查了STL.Net,但它只适用于Visual Studio 2008,它提供容器+算法,但没有智能指针。

有帮助吗?

解决方案

我在代码项目上找到了答案:

Nishant Sivakumar在 http://www.codeproject.com上发表了一篇关于此事的文章/KB/mcpp/CAutoNativePtr.aspx

在这个页面上,还要查看Denis N. Shevchenko的评论:他提供了一个非常有效的类似stl的实现。

其他提示

我还没有彻底测试过这个,但是如下所示:

#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();
    }
};

这可以让您在ref类中互换使用C ++ 11 / Boost的shared_ptrs。

此处记录了STL.Net 。我不知道它处于什么状态或者对你有什么用处。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top