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

标签 c++ boost c++11 shared-ptr

昨天我安装了 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 line 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。这非常有效。

关于c++ - 使用 C++11 复制构造 boost::shared_ptr 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11302758/

相关文章:

c++ - 使用模板化类型调用的模板化仿函数

c++ - 如何有条件地使用 boost MPL 添加?

c++ - 如何在 eclipse makefile 项目的编译器选项中设置 -std=c++0x?

c++ - 'TypeInfo<char>(char * )' isn' t defined but worked pre-C++11; what changed, and how can I fix the error?

c++ - C/C++调用依赖分析引用

c++ - QSerialPort 读取错误的数据计数

c++ - 如何正确处理带有指针的对象的按值返回?

C++ Boost 最大偏差

boost - boost boost::spirit::qi以使用STL容器

class - 将类成员函数传递给 for_each