私はそこに受け入れ答えが既にあるが、これで問題が解決しない参照してください。あなたはC文字列をヌル終端していないので、クライアント側の問題が発生しています。
私はm_stringの型がわからないので、しばらくそれがstd :: stringであると仮定します。あなたは、実際のメソッドを自分で翻訳することができます:クリストフの提案を1として
std::unique_ptr<char[]> MyString::toCString() const
{
// get length (in chars) of string
auto nof_chars = m_string.size();
// allocate that many chars +1 for the null terminator.
auto cString = std::unique_ptr<char[]>{new char[nof_chars + 1]};
// efficiently copy the data - compiler will replace memcpy
// with an ultra-fast sequence of instructions in release build
memcpy(cString.get(), m_string.data(), nof_chars * sizeof(char));
// don't forget to null terminate!!
cString[nof_chars] = '\0';
// now allow RVO to return our unique_ptr
return cString;
}
は、ここで再び、のstd :: copy_nの観点で書かれた方法です。 std :: copy [_xxx]関数群はすべて、最後の書き込みを1回過ぎて処理するイテレータを返します。これを使用して、ヌルターミネータの場所の再計算を保存することができます。標準ライブラリは素晴らしいのではないですか?
std::unique_ptr<char[]> MyString::toCString() const
{
// get length (in chars) of string
auto nof_chars = m_string.size();
// allocate that many chars +1 for the null terminator.
auto cString = std::unique_ptr<char[]>{new char[nof_chars + 1]};
// efficiently copy the data - and don't forget to null terminate
*std::copy_n(m_string.data(), nof_chars, cString.get()) = '\0';
// now allow RVO to return our unique_ptr
return cString;
}
なぜあなたは、スマートポインタを返すされていますか? _C_文字列は 'char'への単なるポインタです(配列ではありません) – ForceBru
' unique_ptr(characters) 'これは意味をなさないのでコンパイルされません。実際のコードを表示します。 –
スマート・ポインタを参照としてスタックに割り当ててから、関数を終了します。その動作が正しいと思われる場合でも、予測できない動作が発生します。 http://stackoverflow.com/questions/10643563/how-to-return-smart-pointers-shared-ptr-by-reference-or-by-value –