title: How to use boost::optional
body: <p>I am trying to use <a href="http://www.boost.org/doc/libs/1_62_0/libs/optional/doc/html/index.html" rel="noreferrer"><code>boost::optional</code></a> as below. </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  #include &lt;boost/optional.hpp&gt;
  
  struct myClass
  {
     int myInt;
     void setInt(int input) { myInt = input; }
     int  getInt(){return myInt; }
  };
  
  boost::optional&lt;myClass&gt; func(const std::string &amp;str)
  {
     boost::optional&lt;myClass&gt; value;
     if(str.length() &gt; 5)
     {
        // If greater than 5 length string. Set value to 10
        value.get().setInt(10);
     }
     else if (str.length() &lt; 5)
     {
        // Else set it to 0
        value.get().setInt(0);
     }
     else
     {
        // If it is 5 set the value to 5
        value.get().setInt(5);
     }
  
     return value;
  }
  
  
  int main()
  {
     boost::optional&lt;myClass&gt; v1 = func("3124");
     boost::optional&lt;myClass&gt; v2 = func("helloWorld");
     boost::optional&lt;myClass&gt; v3 = func("hello");
  
     if (v1)
         std::cout &lt;&lt; "v1 is valid" &lt;&lt; std::endl;
     else
         std::cout &lt;&lt; "v1 is not valid" &lt;&lt; std::endl;
  
     if (v2)
         std::cout &lt;&lt; "v2 is valid" &lt;&lt; std::endl;
     else
        std::cout &lt;&lt; "v3 is not valid" &lt;&lt; std::endl;
  
     if (v3)
        std::cout &lt;&lt; "v3 is valid" &lt;&lt; std::endl;
     else
        std::cout &lt;&lt; "v3 is not valid" &lt;&lt; std::endl;
  
    return 0;
   }
  </code></pre>
  
  <p>I get following error</p>
  
  <blockquote>
    <p>prog.exe:
    /usr/local/boost-1.55.0/include/boost/optional/optional.hpp:631:
    boost::optional::reference_type boost::optional::get() [with T =
    myClass; boost::optional::reference_type = myClass&amp;]: Assertion
    `this->is_initialized()' failed.</p>
  </blockquote>
  
  <p>Presumably, the optional variable is not initialized properly. How to do it the correct way?</p>
  
  <p>EDIT:: Got some very good answers, just couple of more questions 1. Is it a good idea to use <code>make_optional</code> at the end of <code>'func'</code> function and return it? Also 2. I was thinking of assigning <code>boost::none</code> to emphasize that I have no value to assign and that's why <code>boost::none</code>. But not sure if that is valid?   </p>