【问题标题】:AutoPtr in C++/CLI mixed modeC++/CLI 混合模式下的 AutoPtr
【发布时间】:2009-07-16 15:39:55
【问题描述】:

我有一个围绕原生 .lib 和 .h 文件的 C++/CLI 包装器。我在包装类中广泛使用 AutoPtr 类来管理我为包装创建的非托管对象。我遇到了复制构造函数/赋值运算符的障碍。

使用 Kerr 先生的 AutoPtr 类:http://weblogs.asp.net/kennykerr/archive/2007/03/26/AutoPtr.aspx

他建议(在 cmets 中)重新创建赋值运算符的行为:

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”指针从 'const WrapTest::AutoPtr' 到 'WrapTest::AutoPtr %'

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


关于答案的更多背景信息,我从签名中删除了“const”关键字。我知道就复制 ctor 的代码正确性而言,这并没有被嘲笑,但 CLR 根本不喜欢它——有点掩盖了 CLR 的核心与内存管理。

我想知道是否可以将 const 留在签名中,然后使用 GCHandle 或 pin_ptr 确保在执行复制时内存不会移动?

【问题讨论】:

  • 为清楚起见,我在调用 GetPointer() 方法的两行代码中都遇到了该错误。
  • 嗯...我还在考虑这个。你真正想要什么行为?您是否希望在复制 ByteMessage 时丢弃或克隆 ByteMessage 的本机字节消息?也许 ByteMessage 不应该有一个复制构造函数,因为它是一个托管类——ICloneable 怎么样?

标签: c++-cli operator-overloading copy-constructor cautoptr


【解决方案1】:

看看 Kenny Kerr 的 AutoPtr,它在其构造函数中转移所有权——本质上是一个“移动”构造函数,而不是一个复制构造函数。这类似于 std::auto_ptr。

如果您真的想将所有权从 rhs 转移到 this(即不带 NativeByteMessage 的 rhs),您需要将您的复制 ctor 更改为移动 ctor。

另外,你需要使用初始化语法;

// 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 2015-11-02
    • 2011-07-29
    • 1970-01-01
    • 2010-11-07
    • 2011-12-29
    • 2013-01-28
    相关资源
    最近更新 更多