使用 C++11 复制构造 boost::shared_ptr 时出错

Error while copy constructing boost::shared_ptr using C++11

本文关键字:shared 出错 ptr boost C++11 复制 使用      更新时间:2023-10-16

昨天我安装了clang 3.1和g ++ 4.7,并尝试编译我正在处理的项目。我很惊讶地看到它没有使用两个编译器进行编译。但最让我惊讶的是,问题出在boost::shared_ptr.

显然,由于该类定义了移动构造函数/赋值运算符,因此隐式删除了复制构造函数。所以这段代码:

#include <boost/shared_ptr.hpp>
int main() {
    boost::shared_ptr<int> x;
    boost::shared_ptr<int> y(x);
}

不编译。clang 回应此错误:

test.cpp:5:28: error: call to implicitly-deleted copy constructor of
      'boost::shared_ptr<int>'
    boost::shared_ptr<int> y(x);
                           ^ ~
/usr/include/boost/smart_ptr/shared_ptr.hpp:347:5: note: copy constructor is
      implicitly deleted because 'shared_ptr<int>' has a user-declared move
      constructor
    shared_ptr( shared_ptr && r ): px( r.px ), pn() // never throws
    ^

G++ 4.7 提供了类似的错误,也引用了隐式删除的构造函数。奇怪的是,boost::shared_ptr,实际上显式定义了一个复制构造函数(boost/smart_ptr/shared_ptr.hpp 第 228 行):

    template<class Y>
#if !defined( BOOST_SP_NO_SP_CONVERTIBLE )
    shared_ptr( shared_ptr<Y> const & r, typename boost::detail::sp_enable_if_convertible<Y,T>::type = boost::detail::sp_empty() )
#else
    shared_ptr( shared_ptr<Y> const & r )
#endif
    : px( r.px ), pn( r.pn ) // never throws
    {
    }

我正在使用 boost 1.48.0.2,这是相当新的。有谁知道这里发生了什么?为什么在实际定义复制构造函数时没有检测到它?这在较新版本的智能指针库中是否修复?我在更改日志上找不到任何内容。

这是 Boost 中的一个已知错误。Boost 的旧版本(1.48 及更低版本)在 C++11 下不可编译,至少不是全部。就个人而言,我使用此解决方法:

#ifdef MY_LIB_COMPILING_UNDER_CXX11
#include <memory>
namespace my_lib {
using std::shared_ptr;
using std::weak_ptr;
};
#else
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
namespace my_lib {
using boost::shared_ptr;
using boost::weak_ptr;
};
#endif

其中MY_LIB_COMPILING_UNDER_CXX11是你设置的传递给编译器或从编译器的 C++11 标志派生的标志。然后,在图书馆的其余部分,我只使用my_lib::shared_ptr.这效果很好。