【问题标题】:Error while copy constructing boost::shared_ptr using C++11使用 C++11 复制构造 boost::shared_ptr 时出错
【发布时间】:2012-07-02 23:54:04
【问题描述】:

昨天我安装了 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 1.48 不是新的,它已有 8 个月的历史(1.50 是当前版本),并且自从它发布以来,许多 与 C++11 相关的错误修复已经完成。我会说第 1 步是验证这在较新版本的 Boost 中是否有效(或者只使用 std::shared_ptr 代替)。
  • @Gigi 同样的问题。 ildjarn 是的,8 个月大对我来说还算新鲜。问题是我不明白为什么它不起作用,因为实际上定义了复制构造函数。无论如何,我可能不得不更新我的 boost 库。
  • @mfontanini : 8 个月大在 Boost 方面已经相当老了,尤其是在前沿编译器支持方面。 :-]
  • 好吧,我已经更新了 boost,它现在可以工作了:D
  • @mfontanini - 您显示的构造函数不是复制构造函数,因为它是一个模板。它是其他类型的转换构造函数。

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


【解决方案1】:

这是 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。这很好用。

【讨论】:

  • 问题是我没有使用boost::shared_ptr,而是boost::asio。所以我无法做到这一点。无论如何,+1 指出这是一个已知的错误。我可能会做的是 ildjarn 说并更新我的 boost 库。
  • 我检查过,显然它在 1.48.0 版中已修复。但它没有说明是哪个版本,所以我必须假设它是从版本 1.48.0.3 修复的(因为您使用 1.48.0.2 测试但它失败了,而 1.48.0.3 是 1.48.0 中的最后一个小版本)。
  • 感谢您查看!我已经更新到最新版本,现在可以正常使用了。
猜你喜欢
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多