文字列値のプレースホルダとしてchar *(非const)を使用しているサードパーティのライブラリがあります。これらのデータ型に値を割り当てる正しい方法と安全な方法は何ですか?のは、それを警告するコンパイラを取り除く「安全な」方法は、およそコードになりますがchar *文字列を扱う正しい方法は何ですか?
creating c-strings unsafe(?) way...
1.9164 ns
creating c-strings safe(?) way...
31.7406 ns
:
#include "string.h"
#include <iostream>
#include <sj/timer_chrono.hpp>
using namespace std;
int main()
{
sj::timer_chrono sw;
int iterations = 1e7;
// first method gives compiler warning:
// conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
cout << "creating c-strings unsafe(?) way..." << endl;
sw.start();
for (int i = 0; i < iterations; ++i)
{
char* str = "teststring";
}
sw.stop();
cout << sw.elapsed_ns()/(double)iterations << " ns" << endl;
cout << "creating c-strings safe(?) way..." << endl;
sw.start();
for (int i = 0; i < iterations; ++i)
{
char* str = new char[strlen("teststr")];
strcpy(str, "teststring");
}
sw.stop();
cout << sw.elapsed_ns()/(double)iterations << " ns" << endl;
return 0;
}
出力:私は、実行時間を測定するために、自分自身のTimerクラスを使用して、次のテストのベンチマークを持っていますこのベンチマークによれば15-20倍遅くなります(反復ごとに1.9ナノ秒対反復ごとに31.7ナノ秒)。正しい方法とは何か、その "廃止された"方法については何が危険なのでしょうか?
安全なケースで誰がメモリを解放しますか?正直言って、第三者図書館はひどく設計されています。 –
一時バッファにコピーする場合は、少なくとも「ベクトル」を使用してください。 –
* Aside *: 'new char [strlen(" teststr ")+ 1]'バッファの外側にNUL文字を書くのを避けるためです。 –