vs2010使用BOOST_MOVABLE_BUT_NOT_COPYABLE构建错误

时间:2014-08-26 09:08:23

标签: c++ visual-studio-2010 boost move

以下是简化代码:

-------------- 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:未解析的外部符号&#34;私有:__ cdecl foo(类foo const&amp;)&#34;在函数中引用&#34;类boost :: shared_ptr __cdecl boost :: make_shared const&gt;(类boost :: reference_wrapper const&amp;&amp;)&#34;

你可以提出任何建议吗?谢谢!

1 个答案:

答案 0 :(得分:3)

您需要使用boost::move()

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

否则,编译器正在尝试访问复制构造函数foo(const foo&),由于此类型为noncopyable,因此无法访问该复制构造函数boost::moveBOOST_RV_REF(foo)将值转换回r值引用(或隐藏在foo(BOOST_RV_REF(foo) other)后面的任何模拟C ++ 03中r值引用的内容),正确调用{{1}}。< / p>