Avoiding Checking likely if
<p>Given the following:</p>

<pre><code>class ReadWrite {
public:
    int Read(size_t address);
    void Write(size_t address, int val);
private:
    std::map&lt;size_t, int&gt; db;
}
</code></pre>

<p>In read function when accessing an address which no previous write was made to I want to either throw exception designating such error or allow that and return 0, in other words I would like to either use <code>std::map&lt;size_t, int&gt;::operator[]()</code> or <code>std::map&lt;size_t, int&gt;::at()</code>, depending on some bool value which user can set. So I add the following:</p>

<pre><code>class ReadWrite {
public:
    int Read(size_t add) { if (allow) return db[add]; return db.at(add);}
    void Write(size_t add, int val) { db[add] = val; }
    void Allow() { allow = true; }
private:
    bool allow = false;
    std::map&lt;size_t, int&gt; db;
}
</code></pre>

<p>The problem with that is:
Usually, the program will have one call of allow or none at the beginning of the program and then afterwards many accesses. So, performance wise, this code is bad because it every-time performs the check <code>if (allow)</code> where usually it's either always true or always false.
So how would you solve such problem?</p>

<p><strong>Edit:</strong></p>

<p>While the described use case (one or none <code>Allow()</code> at first) of this class is very likely it's not definite and so I must allow user call <code>Allow()</code> dynamically.</p>

<p><strong>Another Edit:</strong></p>

<p>Solutions which use function pointer: What about the performance overhead incurred by using function pointer which is not able to make inline by the compiler? If we use <code>std::function</code> instead will that solve the issue?</p>