题
一个如何可以转换指向const对象到指向一个非const对象一个shared_ptr一个shared_ptr。 我试图做到以下几点:
boost::shared_ptr<const A> Ckk(new A(4));
boost::shared_ptr<A> kk=const_cast< boost::shared_ptr<A> > Ckk;
但是,这是行不通的。
解决方案
“的boost :: const_pointer_cast”会做你要求什么,但答案的强制性下半场的是,你可能不应该使用它。当它好像你需要抛弃变量的常量财产99%的时间,这意味着你有一个设计缺陷。常量有时比只是窗口敷料和铸造它扔掉可能会导致意外的错误更多。
不知道你的情况更多的细节可以说不准。但是,没有常量播的讨论是完全没有提到这一事实。
其他提示
使用boost::const_pointer_cast
,文档。
适当的方式应该是这样的
boost::shared_ptr<A> kk (boost::const_pointer_cast<A>(Ckk));
std::const_cast_pointer
使得第二管理指针。中投之后,你有一个写指针的和的原const的指针。指针对象保持不变。引用计数已经增加了1。
请注意const_cast
是一个内置的关键字,但const_pointer_cast
是命名空间std
模板函数。
在可写指针然后可用于将值从shared_ptr<const T>
下发生变化。恕我直言,可写指针只应暂时坚持在堆栈上;否则必须有一个设计缺陷。
我曾经写了一个小的测试程序,以明确这一点对我自己,我适合这个主题:
#include <memory>
#include <iostream>
#include <cassert>
using namespace std;
typedef shared_ptr<int> int_ptr;
typedef shared_ptr<const int> const_int_ptr;
int main(void)
{
const_int_ptr Ckk(new int(1));
assert(Ckk.use_count() == 1);
cout << "Ckk = " << *Ckk << endl;
int_ptr kk = const_pointer_cast<int>(Ckk); // obtain a 2nd reference
*kk = 2; // change value under the const pointer
assert(Ckk.use_count() == 2);
cout << "Ckk = " << *Ckk << endl; // prints 3
}
在UNIX或Windows / Cygwin的,编译
g++ -std=c++0x -lm const_pointer_cast.cpp
不隶属于 StackOverflow