title: C++ prevent access to a temporary
body: <p>I am working on a class that acts like a <code>std::variant</code>, in that, it stores another object using a union along with an error code. Like <code>std::variant</code>, there is a <code>get_if()</code> function that can be used to access to the object in the class. So something like this</p>
  
  <pre><code>template&lt;typename T&gt;
  class result final 
  {
      ...
      [[nodiscard]] constexpr T const *
      get_if() const noexcept
      {
          if (details::result_type::contains_t == m_which) {
              return &amp;m_t;
          }
  
          return nullptr;
      }
      ...
  };
  </code></pre>
  
  <p>Now... suppose you have a function that returns an object using this class like this:</p>
  
  <pre><code>[[nodiscard]] static bsl::result&lt;example_implementation&gt;
  make(bsl::int32 const answer) noexcept
  {
      constexpr bsl::int32 valid_answer{42};
  
      if (answer == valid_answer) {
          return {bsl::in_place, valid_answer};
      }
  
      return {bsl::errc_failure, bsl::here()};
  }
  </code></pre>
  
  <p>All of this works great. The problem that I cam concerned about is if the user does something like this:</p>
  
  <pre><code>if (auto const impl = example_implementation::make(valid_answer).get_if()) {
      example_bind_apis_type enforced_impl{*impl};
  
      if (enforced_impl.member_func_example(valid_answer)) {
          bsl::print("success\n");
      }
  
      if (!enforced_impl.member_func_example(invalid_answer)) {
          bsl::print("success\n");
      }
  }
  else {
      bsl::print("failure\n");
  }
  </code></pre>
  
  <p>In the example above, the user is creating an example_implementation, and then using <code>get_if()</code> to get a pointer to the object wrapped by the result object. That pointer is then dereferenced and used. ASAN detects that the stack was used after destruction of an object, which is due to the fact that the "if" statement created a temporary result object, and then returned a pointer to something inside that temporary, which is deleted after the call to <code>get_if()</code>. This is similar to an issue with <code>QString</code> that I remember years ago, when people would get a pointer to the C style string inside the <code>QString</code> from a temporary. </p>
  
  <p>Is there a way, in C++ to prevent the user from being able to call <code>get_if()</code> on a temporary like this? I tried reference qualifying <code>get_if()</code>, but that doesn't seem to work as the make function above returns an lvalue, not an rvalue (even though RVO will likely remove the copy). All I want to do is prevent the user from making this mistake accidentally. </p>
  
  <p><strong>Update:</strong>
  As stated in the comments, make() is returning an rvalue, not an lvalue as I stated above, so a ref qualifier should work. </p>