What exactly is invalidation of reference/pointer?

本小妞迷上赌 提交于 2021-01-27 05:28:41

问题


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?


回答1:


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.




回答2:


For example:

std::string * p_s(new ::std::string("abc"));
std::string s2(*p_s); // shares buffer with p_s
char const & ch1(static_cast<::std::string const &>(*p_s)[0]);
char const & ch2(static_cast<::std::string const &>(s2)[0]); // same as ch1
// CoW, ch2 becomes invalid, but is backed by p_s buffer
char & ch(static_cast<::std::string &>(s2)[0]); // backed by new buffer
// both ch1 and ch2 become invalid
delete p_s;


来源:https://stackoverflow.com/questions/51748529/what-exactly-is-invalidation-of-reference-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!