【问题标题】:how to convert char * to boost::shared_ptr?如何将 char * 转换为 boost::shared_ptr?
【发布时间】:2017-10-08 14:33:41
【问题描述】:

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

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

【问题讨论】:

标签: c++ boost


【解决方案1】:

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

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 );

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2011-03-28
    • 2013-04-25
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    相关资源
    最近更新 更多