【发布时间】:2017-10-08 14:33:41
【问题描述】:
我有一个普通指针char *,如何将char *转换为boost::shared_ptr?
char *str = "abcdfg";
boost::shared_ptr<char> ss = ?(str);
【问题讨论】:
-
当
shared_ptr尝试删除你的字符串文字时,你认为会发生什么?
我有一个普通指针char *,如何将char *转换为boost::shared_ptr?
char *str = "abcdfg";
boost::shared_ptr<char> ss = ?(str);
【问题讨论】:
shared_ptr 尝试删除你的字符串文字时,你认为会发生什么?
您不能将字符串文字转换为共享指针。让我“更正”你的代码,然后你剩下的就是未定义的行为:
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 );
【讨论】: