1 /*=============================================================================
2 Copyright (c) 2006 Joao Abecasis
3 http://spirit.sourceforge.net/
5 Distributed under the Boost Software License, Version 1.0. (See accompanying
6 file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 =============================================================================*/
8 #if !defined(BOOST_SPIRIT_STATIC_HPP)
9 #define BOOST_SPIRIT_STATIC_HPP
11 #include <boost/noncopyable.hpp>
12 #include <boost/call_traits.hpp>
13 #include <boost/aligned_storage.hpp>
15 #include <boost/type_traits/add_pointer.hpp>
16 #include <boost/type_traits/alignment_of.hpp>
18 #include <boost/thread/once.hpp>
20 #include <memory> // for placement new
22 #include <boost/spirit/home/classic/namespace.hpp>
24 namespace boost { namespace spirit {
26 BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN
29 // Provides thread-safe initialization of a single static instance of T.
31 // This instance is guaranteed to be constructed on static storage in a
32 // thread-safe manner, on the first call to the constructor of static_.
35 // T is default constructible
36 // (There's an alternate implementation that relaxes this
37 // requirement -- Joao Abecasis)
38 // T::T() MUST not throw!
39 // this is a requirement of boost::call_once.
41 template <class T, class Tag>
51 static_::get_address()->~value_type();
57 static void construct()
59 ::new (static_::get_address()) value_type();
67 typedef typename boost::call_traits<T>::reference reference;
68 typedef typename boost::call_traits<T>::const_reference const_reference;
72 boost::call_once(&default_ctor::construct, constructed_);
80 operator const_reference() const
87 return *this->get_address();
90 const_reference get() const
92 return *this->get_address();
96 typedef typename boost::add_pointer<value_type>::type pointer;
98 static pointer get_address()
100 return static_cast<pointer>(data_.address());
103 typedef boost::aligned_storage<sizeof(value_type),
104 boost::alignment_of<value_type>::value> storage_type;
106 static storage_type data_;
107 static once_flag constructed_;
110 template <class T, class Tag>
111 typename static_<T, Tag>::storage_type static_<T, Tag>::data_;
113 template <class T, class Tag>
114 #ifndef BOOST_THREAD_PROVIDES_ONCE_CXX11
115 once_flag static_<T, Tag>::constructed_ = BOOST_ONCE_INIT;
117 once_flag static_<T, Tag>::constructed_;
120 BOOST_SPIRIT_CLASSIC_NAMESPACE_END
122 }} // namespace BOOST_SPIRIT_CLASSIC_NS
124 #endif // include guard