如何避免使用memcpy创建字符串

问题描述 投票:0回答:1

我的程序员有很多记忆。我想避免它们。

我想获得一个类似boost :: string_ref的结构。我想知道。

uint32_t len = 20;
char *p = new char[len];
memset(p, 0x00, len)
memcpy(p, "aaaa", 4);
string str(p, 4);// whether is use memcpy or not ?
const string str2(p, 4); //whether is use memcpy or not
//if it used memcpy, how to avoid memcpy ?

string_ref->字符串

string_view-> string

string-> string_ref

string-> string_view

字符*->字符串

字符串->字符串

请告诉我如何判断函数是否使用了memcpy吗?

c++ c++17
1个回答
0
投票

使用std::string_view避免复制字符串。

#include <string_view>
// ...

const string_view strview(p, 4);

请注意,不能保证字符串视图以null终止,因此在需要以null终止char*的API中使用字符串视图时要格外小心。另外,当他们正在查看的字符串超出范围时,字符串视图本身将变得无效(就像指针一样。)

© www.soinside.com 2019 - 2024. All rights reserved.