我周围天然的.lib和.h文件一个C ++ / CLI包装。我用的是AutoPtr类相当广泛的包装类来管理我的包裹创建非托管对象。我打了一个路障与拷贝构造函数/赋值运算符。

使用从克尔先生的AutoPtr类: HTTP: //weblogs.asp.net/kennykerr/archive/2007/03/26/AutoPtr.aspx

他提出了以下(评价)重新赋值操作的行为:

SomeManagedClass->NativePointer.Reset(new NativeType);

我相信这是真的。但是,当我编译我的代码:

ByteMessageWrap (const ByteMessageWrap% rhs)
{
     AutoPtr<ByteMessage> m_NativeByteMessage(rhs.m_NativeByteMessage.GetPointer());
};

ByteMessageWrap% operator=(const ByteMessageWrap% rhs)
{
     //SomeManagedClass->NativePointer.Reset(new NativeType);
     if (this == %rhs) // prevent assignment to self
        return *this;

     this->m_NativeByteMessage.Reset(rhs.m_NativeByteMessage.GetPointer());
     return *this;
};

- 我收到以下错误:

  

错误C2662:   'WrapTest :: AutoPtr :: GetPointer':   不能转换this指针从   '常量WrapTest :: AutoPtr' 来   'WrapTest :: AutoPtr%'

有没有人遇到过类似的问题?


有关的答案进一步的背景,我删除从签名“常量”关键字。我知道这是不是在代码正确性拷贝构造函数而言笑了,但却CLR不喜欢它 - 有点掩盖在其与内存管理核心CLR。

我不知道是否有可能离开常量的签名,然后使用的GCHandle或pin_ptr以确保内存不会在您移动在执行复制?

有帮助吗?

解决方案

看着肯尼 - 科尔的AutoPtr,它转移在其构造所有权 - 本质上是一个“移动”的构造函数,而不是一个拷贝构造函数。这与标准:: auto_ptr的类似。

如果你真的想从RHS将所有权转让给本(即离开RHS没有它NativeByteMessage),你需要改变你的拷贝构造函数为移动构造函数。

此外,还需要使用初始化语法;

// warning - code below doesn't work
ByteMessageWrap (ByteMessageWrap% rhs)
    : m_NativeByteMessage(rhs.m_NativeByteMessage); // take ownership
{
}

ByteMessageWrap% operator=(ByteMessageWrap% rhs)
{
     //SomeManagedClass->NativePointer.Reset(new NativeType);
     if (this == %rhs) // prevent assignment to self
        return *this;

     m_NativeByteMessage.Reset(rhs.m_NativeByteMessage.Release());
     return *this;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top