我有一个第三方库,它使用 char* (非常量)作为字符串值的占位符。将值分配给这些数据类型的正确且安全的方法是什么?我有以下测试基准,它使用我自己的计时器类来测量执行时间:
#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;
}
输出:
creating c-strings unsafe(?) way...
1.9164 ns
creating c-strings safe(?) way...
31.7406 ns
虽然“安全”方式摆脱了编译器警告,但根据这个基准,它使代码慢了大约 15-20 倍(每次迭代 1.9 纳秒 vs 每次迭代 31.7 纳秒)。什么是正确的方法,这种“已弃用”的方法有什么危险?