Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is invalidation of reference/pointer?

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?

like image 463
Daniel Langr Avatar asked Aug 08 '18 13:08

Daniel Langr


1 Answers

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.

like image 67
Lightness Races in Orbit Avatar answered Oct 18 '22 23:10

Lightness Races in Orbit