引用/指针的无效到底是什么? [英] What exactly is invalidation of reference/pointer?
问题描述
在标准中找不到指针/引用无效的任何定义.我问是因为我刚刚发现C ++ 11禁止对字符串进行写时复制(COW).据我了解,如果应用了COW,则在以下命令之后, p
仍然是有效的指针,而 r
仍然是有效的引用:
std :: string s("abc");std :: string s2(s);char * p =&(s2 [0]);字符和r = s2 [0];s2 [1] ="B";
只是他们不再指向/引用 s2
的第一个字符,而只是指向/引用 s
的第一个字符.
在C ++ 11标准中,据说非恒定的 std :: basic_string :: operator []
可能不会使对字符串元素的指针/引用(以及迭代器)无效./p>
哪个规则说,如果实施了COW,则上面显示的示例实际上会使 p
和 r
无效?
标准中没有对无效"的定义,因为该术语是从英语继承而来的.它的意思是英语:无效的引用/指针不再有效.无法使用.
但是,在某些地方明确指出了此约束.例如,将指针左值转换为右值时(发生在表达式求值过程中):
[conv.lval/2]
否则,如果glvalue引用的对象包含无效的指针值(3.7.4.2、3.7.4.3),则该行为是实现定义的>
我现在找不到引用的用语,但是无论如何,您不能使用对不再存在的引用进行引用是不言而喻的.
I cannot find any definition for invalidation of pointers/references in the Standard. I ask because I just found out that C++11 forbids copy-on-write (COW) for strings. As far as I understand, if COW was applied then p
would be still a valid pointer and r
a valid reference after the following commands:
std::string s("abc");
std::string s2(s);
char * p = &(s2[0]);
char & r = s2[0];
s2[1] = "B";
Just they would no longer point/refer to the first character of s2
, but merely to the first character of s
.
In the C++11 Standard, it is said that non-constant std::basic_string::operator[]
may not invalidate pointers/references (and also iterators) to string elements.
Which rules say that the above shown example would actually invalidate p
and r
if COW was implemented?
There is no definition for "invalidation" in the standard because the term is inherited from English. It means what it means in English: an invalidated reference/pointer is no longer valid. It cannot be used.
There are, however, places where this constraint is explicitly noted. For example, when converting a pointer lvalue to an rvalue (which happens during evaluation of an expression):
[conv.lval/2]
Otherwise, if the object to which the glvalue refers contains an invalid pointer value (3.7.4.2, 3.7.4.3), the behavior is implementation-defined
I can't find the wording for references right now, but it's anyway self-explanatory that you cannot use a reference to something that no longer exists.
这篇关于引用/指针的无效到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!