char * /字符串连接不复制? [英] char*/string concatenation without copying?
问题描述
我想在C或C ++中连接2个字符串,而不需要新的内存分配和复制。是否有可能?
I would like to concatenate 2 strings in C or C++ without new memory allocation and copying. Is it possible?
可能的C代码:
char* str1 = (char*)malloc(100);
char* str2 = (char*)malloc(50);
char* str3 = /* some code that concatenates these 2 strings
without copying to occupy a continuous memory region */
然后,当我不再需要它们时,我只需:
Then, when I don't need them any more, I just do:
free(str1);
free(str2);
或者如果可能,我想在C ++中使用 std :: string
或者 char *
,但使用 new
和<$ c $ str3上的 void operator delete(void * ptr,std :: size_t sz)
。
Or if possible, I would like to achieve the same in C++, using std::string
or maybe char*
, but using new
and delete
(possibly void operator delete ( void* ptr, std::size_t sz )
operator (C++14) on the str3).
有很多关于字符串连接的问题,但我还没有找到一个问题。
There are a lot of questions about strings concatenation, but I haven't found one that asks the same.
推荐答案
不,不可能
在C中,malloc操作返回内存块彼此没有关系。但在C中,字符串必须是连续的字节数组。因此,没有办法在不复制的情况下扩展str1,更不用说连接。
In C, malloc operations return blocks of memory that have no relationship to each other. But in C, strings must be a continuous array of bytes. So there is no way to extend str1 without copying, let alone concatenate.
对于C ++,可能会感兴趣的是:查看此答案。
For C++, perhaps ropes may be of interest: See this answer.
绳索以不必连续的块分配。这支持O(1)级联。但是,访问器使其显示为单个字节字符串。我敢肯定,要将绳子转换回std :: string或C风格的字符串将需要一个副本,但这可能是最接近你想要的。
Ropes are allocated in chunks that do not have to be contiguous. This supports O(1) concatenation. However, the accessors make it appear as a single string of bytes. I'm certain that to convert ropes back to std::string or C style strings will take a copy however, but this is probably the closest to what you want.
此外,它可能是一个过早的优化,担心复制几个字符串的成本。除非您正在移动批次的资料,否则无关紧要
Also, it is probably a premature optimization to worry about the costs of copying a few strings around. Unless you are moving lots of data, it won't matter
这篇关于char * /字符串连接不复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!