将std :: string附加到自身是否安全? [英] Is it safe to append std::string to itself?
问题描述
考虑这样的代码:
std::string str = "abcdef";
const size_t num = 50;
const size_t baselen = str.length();
while (str.length() < num)
str.append(str, 0, baselen);
像这样对自身调用 std :: basic_string< T> :: append()
是否安全?复制操作之前无法通过放大使源内存无效吗?
Is it safe to call std::basic_string<T>::append()
on itself like this? Cannot the source memory get invalidated by enlarging before the copy operation?
我在该方法特有的标准中找不到任何内容.它说上面的内容等同于 str.append(str.data(),baselen)
,我认为这可能并不完全安全,除非在 append(constchar *,size_t)
.
I could not find anything in the standard specific to that method. It says the above is equivalent to str.append(str.data(), baselen)
, which I think might not be entirely safe unless there is another detection of such cases inside append(const char*, size_t)
.
我检查了一些实现,它们似乎是一种安全的方式,但是我的问题是这种行为是否可以保证.例如."将std :: vector附加到自身,未定义的行为吗?"用于 std :: vector
.
I checked a few implementations and they seemed safe one way or another, but my question is if this behavior is guaranteed. E.g. "Appending std::vector to itself, undefined behavior?" says it's not for std::vector
.
推荐答案
根据§21.4.6.2/§21.4.6.3:
According to §21.4.6.2/§21.4.6.3:
函数[
basic_string&append(const charT * s,size_type n);
]将由* this控制的字符串替换为一个长度为size()+ n的字符串,该字符串的第一个size()元素是原始字符串的副本由* this控制,其余元素是s的前n个元素的副本.
The function [
basic_string& append(const charT* s, size_type n);
] replaces the string controlled by *this with a string of length size() + n whose first size() elements are a copy of the original string controlled by *this and whose remaining elements are a copy of the initial n elements of s.
注意:这适用于每个 append
调用,因为每个 append
都可以按照 append(const charT *,size_type)
,由标准(第21.4.6.2/§21.4.6.3条)定义.
Note: This applies to every append
call, as every append
can be implemented in terms of append(const charT*, size_type)
, as defined by the standard (§21.4.6.2/§21.4.6.3).
因此,基本上, append
会复制 str
(我们将其复制为 strtemp
),并附加 n
将 str2
的字符转换为 strtemp
,然后将 str
替换为 strtemp
.
So basically, append
makes a copy of str
(let's call the copy strtemp
), appends n
characters of str2
to strtemp
, and then replaces str
with strtemp
.
对于 str2
是 str
的情况,没有任何变化,因为在分配临时副本时(而不是在分配临时副本时)字符串会被放大.
For the case that str2
is str
, nothing changes, as the string is enlarged when the temporary copy is assigned, not before.
即使未在标准中明确声明,也可以通过 std :: basic_string< T> :: append
的定义来保证(如果实现与标准完全相同).
Even though it is not explicitly stated in the standard, it is guaranteed (if the implementation is exactly as stated in the standard) by the definition of std::basic_string<T>::append
.
因此,这不是未定义的行为.
Thus, this is not undefined behavior.
这篇关于将std :: string附加到自身是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!