Can I safely create references to possibly invalid memory as long as I don't use it?
<p>I want to parse UTF-8 in C++. When parsing a new character, I don't know in advance if it is an ASCII byte or the leader of a multibyte character, and also I don't know if my input string is sufficiently long to contain the remaining characters.</p>

<p>For simplicity, I'd like to name the four next bytes <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code>, and because I am in C++, I want to do it using references.</p>

<p>Is it valid to define those references at the beginning of a function as long as I don't access them before I know that access is safe? Example:</p>

<pre><code>void parse_utf8_character(const string s) {
    for (size_t i = 0; i &lt; s.size();) {
        const char &amp;a = s[i];
        const char &amp;b = s[i + 1];
        const char &amp;c = s[i + 2];
        const char &amp;d = s[i + 3];

        if (is_ascii(a)) {
            i += 1;
            do_something_only_with(a);
        } else if (is_twobyte_leader(a)) {
            i += 2;
            if (is_safe_to_access_b()) {
                do_something_only_with(a, b);
            }
        }
        ...
     }
}
</code></pre>

<p>The above example shows what I want to do semantically. It doesn't illustrate why I want to do this, but obviously real code will be more involved, so defining b,c,d only when I know that access is safe and I need them would be too verbose.</p>
