2008-10-06 34 views
6

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

下面是一个例子:

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 ! 

}; 

有谁知道的shared_ptr在C++/CLI世界等同呢?

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

+0

http://codereview.stackexchange.com/questions/1695/scoped-ptr-for-c-cli-ensure-managed-object-properly-frees-owned-native-object – 2014-04-09 12:48:04

回答

2

我找到了答案上codeproject

NISHANT西瓦库玛上发布有关此文章在http://www.codeproject.com/KB/mcpp/CAutoNativePtr.aspx

在这个页面上,也期待由丹尼斯·N.舍甫琴科评论:他提供了一个STL样实现这工作得很好。

+0

请避免链接,他们可以得到破碎 – 2015-11-26 11:03:24

1

我还没有彻底测试这一点,但如何对类似如下:

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

这应该让你在裁判类使用C++ 11/Boost的shared_ptrs interchangebly。