2010-06-10 170 views
4

我想將一個常量從boost::shared_ptr中刪除,但我不是boost::const_pointer_cast的答案。 boost::const_pointer_cast想要const boost::shared_ptr<T>,而不是boost::shared_ptr<const T>。讓我們放棄強制性的「你不應該這樣做」。我知道......但我需要這樣做......那麼做到最好/最簡單的方法是什麼?boost :: shared_ptr <const T> boost :: shared_ptr <T>

爲了清楚起見:

boost::shared_ptr<const T> orig_ptr(new T()); 

boost::shared_ptr<T> new_ptr = magic_incantation(orig_ptr); 

我需要知道magic_incantation()

回答

9

boost::const_pointer_cast你想使用的功能:

boost::shared_ptr<const int> ci(new int(42)); 
boost::shared_ptr<int> i(boost::const_pointer_cast<int>(ci)); 

這是否不工作您?我測試了Boost 1.43和Visual C++ 2010 C++ 0x實現 - 沒有任何問題。

+0

其實...當我指定的模板參數,它確實爲我工作。出於某種原因,當我第一次使用它時被編譯器的錯誤信息所愚弄。謝謝。 – Flevine 2010-06-10 01:20:17

+0

@Flevine:是的,'const_pointer_cast',就像C++'const_cast'一樣,可以添加或刪除const和volatile限定符,所以不需要指定它就可以獲得所需的目標資格。我很高興獲得幫助。 – 2010-06-10 01:30:06

2

注意,其他「股東」會很驚訝,至少可以說,如果共享const T突然發生變化......

相關問題