c++ how to deal with method returning either NULL or std::string?


<p>I am a bit stuck with some code. I have to use the return type of the method <code>getToto()</code> which usually returns a <code>std::string</code>, but in one case it returns <code>false</code> (It is part of a library I have to use, I cannot modify it). I understand that is equivalent to a null pointer. But I cannot find a proper way to catch it!</p>

<p><strong>Test.cpp</strong></p>

<pre class="lang-cpp prettyprint-override"><code>static std::string getToto(){
 char buffer[1024];
 if ( CTX_Get_Env(buffer, "Toto", 1024) )
    return false;
 return buffer;
}
</code></pre>

<p>If I try</p>

<pre class="lang-cpp prettyprint-override"><code>const char* returned = Test::getToto().c_str();
if (returned==NULL){
    std::cout&lt;&lt; "null pointer"&lt;&lt;std::endl;
}
</code></pre>

<p>I get an error whilst running</p>

<blockquote>
  <p>terminate called after throwing an instance of 'std::logic_error'</p>
  
  <p>what():  basic_string::_S_construct NULL not valid</p>
</blockquote>

<p>Sorry, I have a rather low level in C++.</p>
