[英]Error while copy constructing boost::shared_ptr using C++11
昨天我安裝了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,這是相當新的。 有誰知道這里發生了什么? 為什么復制構造函數在實際定義時未被檢測到? 這是在較新版本的智能指針庫中修復的嗎? 我在changelogs上找不到任何東西。
這是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
。 這非常有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.