首页 文章

vs2010使用BOOST_MOVABLE_BUT_NOT_COPYABLE构建错误

提问于
浏览
0

以下是简化代码:

-------------- class foo -----------------------

class foo : private boost::noncopyable      //--- mark 1---
{
    BOOST_MOVABLE_BUT_NOT_COPYABLE(foo)     //--- mark 2---

public:

    /**
     * Move constructor.
     */
    foo(BOOST_RV_REF(foo) other);

    /**
     * Move-assignment.
     */
    foo& operator=(BOOST_RV_REF(foo) other);

    /**
     * Releases
     */
    ~foo();
    ......
private:
    fool_impl*  m_pimpl;
}

foo::foo(foo_impl* pimpl)
:m_pimpl(pimpl) 
{}

foo::foo(
    BOOST_RV_REF(foo) other) : m_pimpl(other.m_pimpl)
{
    other.m_pimpl = NULL;
}

foo& foo::operator=(
    BOOST_RV_REF(foo) other)
{
    if (&other != this)
    {
        delete m_pimpl;
        m_pimpl = other.m_pimpl;
        other.m_pimpl = NULL;
    }

    return *this;
}

foo::~foo()
{
    delete m_pimpl;
}

---------------班吧-----------

class bar
{
public:

    explicit bar(BOOST_RV_REF(foo) other);

    ......

private:

    foo m_foo;
};

bar::bar(BOOST_RV_REF(foo) other)
:
m_foo(other)                        //--- mark 3----
{}

使用VS2010构建时,标记3报告错误:

error C2248: 'foo' : cannot access private member declared in class 'foo'
1>   mark 1:  see declaration of 'foo'
1>   mark 2:  see declaration of 'foo'

我试图修改一些代码,但没用 . 有人可以提出任何建议吗?谢谢 .


@Piotr S.感谢您的回答,我试过,错误消失了,但又出现了另一个错误:

class test
{
public:

    explicit test(
        BOOST_RV_REF(foo) other);

private:
    boost::shared_ptr<aClass> m_class;
};

test::test(BOOST_RV_REF(foo) other)
{
    m_class = boost::make_shared<aClass>(boost::ref(other));
}

错误LNK2019:未解析的外部符号“private:__ cdecl foo(class foo const&)”在函数“class boost :: shared_ptr __cdecl boost :: make_shared const>(类boost :: reference_wrapper const &&)”中引用

你能提出什么建议吗?谢谢!

1 回答

  • 3

    您需要使用 boost::move()

    bar::bar(BOOST_RV_REF(foo) other)
    :
        m_foo(boost::move(other)) // move it !
    {}
    

    否则,编译器正在尝试访问复制构造函数 foo(const foo&) ,这是不可访问的,因为此类型是 noncopyable . boost::move 将值转换回r值引用(或隐藏在 BOOST_RV_REF(foo) 后面的任何模拟C 03中r值引用的内容),正确调用 foo(BOOST_RV_REF(foo) other) .

相关问题