如何将char *转换为boost :: shared_ptr?

时间:2017-05-10 05:17:46

标签: c++ boost

我有一个普通指针char *,如何将char *转换为boost::shared_ptr

char *str = "abcdfg";
boost::shared_ptr<char> ss = ?(str);

1 个答案:

答案 0 :(得分:6)

您无法将字符串文字转换为共享指针。让我只是“纠正”你的代码,然后剩下的就是未定义的行为

const char *str = "abcdfg";
boost::shared_ptr<char> ss(str);

现在,这将编译,但它会产生严重的问题,因为str不是动态分配的内存。一旦共享指针被破坏,您将得到未定义的行为。

所以,如果你想要那个字符串,你必须先复制它:

const char *str = "abcdfg";
boost::shared_ptr<char> ss( new char[std::strlen(str)+1] );
std::strcpy( ss.get(), str );

但是,如果您只是为了在字符串上使用RAII语义,为什么不首先使用std::string

std::string sss( str );