Member fun value() that throws on uninitialized

This commit is contained in:
Andrzej Krzemienski
2014-05-22 23:32:49 +02:00
parent 5e59e10f93
commit 75271b73a8
11 changed files with 226 additions and 6 deletions

View File

@ -0,0 +1,28 @@
// Copyright (C) 2014, Andrzej Krzemienski.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/optional for documentation.
//
// You are welcome to contact the author at:
// akrzemi1@gmail.com
//
#ifndef BOOST_BAD_OPTIONAL_ACCESS_22MAY2014_HPP
#define BOOST_BAD_OPTIONAL_ACCESS_22MAY2014_HPP
#include <stdexcept>
namespace boost {
class bad_optional_access : public std::logic_error
{
public:
explicit bad_optional_access(const std::string& what_arg) : std::logic_error(what_arg) {}
explicit bad_optional_access(const char* what_arg) : std::logic_error(what_arg) {}
};
} // namespace boost
#endif

View File

@ -23,7 +23,9 @@
#include <boost/config.hpp>
#include <boost/assert.hpp>
#include <boost/bad_optional_access.hpp>
#include <boost/static_assert.hpp>
#include <boost/throw_exception.hpp>
#include <boost/type.hpp>
#include <boost/type_traits/alignment_of.hpp>
#include <boost/type_traits/has_nothrow_constructor.hpp>
@ -935,6 +937,22 @@ class optional : public optional_detail::optional_base<T>
// No-throw
reference_const_type operator *() const { return this->get() ; }
reference_type operator *() { return this->get() ; }
reference_const_type value() const
{
if (this->is_initialized())
return this->get() ;
else
throw_exception(bad_optional_access("Attempted to access the value of an uninitialized optional object."));
}
reference_type value()
{
if (this->is_initialized())
return this->get() ;
else
throw_exception(bad_optional_access("Attempted to access the value of an uninitialized optional object."));
}
bool operator!() const BOOST_NOEXCEPT { return !this->is_initialized() ; }

View File

@ -11,11 +11,9 @@
//
// Revisions:
// 10 May 2008 (added swap related forward declaration) Niels Dekker
// 17 Apr 2014 (added noexcept) Andrzej Krzemienski
//
#ifndef BOOST_OPTIONAL_OPTIONAL_FWD_FLC_19NOV2002_HPP
#define BOOST_OPTIONAL_OPTIONAL_FWD_FLC_19NOV2002_HPP
#include <boost/config.hpp>
namespace boost {