Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

Using smart pointers with Boost.Intrusive containers

Boost , The Boost C++ Libraries BoostBook Documentation Subset , Chapter 17. Boost.Intrusive

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

НавязчивыйКрюки могут быть сконфигурированы для использования других указателей, чем необработанные указатели. Когданапрягает.Крюк сконфигурирован с умным указателем в качестве аргумента, эта конфигурация указателя передается контейнерам. Например, если следующий крюк выполнен с умным указателем (например, офсетным указателем отBoost.Interprocess).:

#include <boost/intrusive/list.hpp>
#include <boost/interprocess/offset_ptr.hpp>
using namespace boost::intrusive;
namespace ip = boost::interprocess;
class shared_memory_data
   //Declare the hook with an offset_ptr from Boost.Interprocess
   //to make this class compatible with shared memory
   :  public list_base_hook< void_pointer< ip::offset_ptr<void> > >
{
   int data_id_;
   public:
   int get() const   {  return data_id_;  }
   void set(int id)  {  data_id_ = id;    }
};

Любой интрузивный список, построенный с использованием этого крючка, будет готов для совместной памяти, потому что интрузивный список также будет использовать офсетные указатели внутри. Например, мы можем создать назойливый список в общей памяти, объединяющийBoost.InterprocessиBoost.Intrusive:

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
//Definition of the shared memory friendly intrusive list
typedef list<shared_memory_data> intrusive_list_t;
int main()
{
   //Now create an intrusive list in shared memory:
   //nodes and the container itself must be created in shared memory
   const int MaxElem    = 100;
   const int ShmSize    = 50000;
   const char *ShmName  = get_shared_memory_name();
   {
      //Erase all old shared memory
      ip::shared_memory_object::remove(ShmName);
      ip::managed_shared_memory shm(ip::create_only, ShmName, ShmSize);
      //Create all nodes in shared memory using a shared memory vector
      //See Boost.Interprocess documentation for more information on this
      typedef ip::allocator
         < shared_memory_data, ip::managed_shared_memory::segment_manager>
            shm_allocator_t;
      typedef ip::vector<shared_memory_data, shm_allocator_t> shm_vector_t;
      shm_allocator_t shm_alloc(shm.get_segment_manager());
      shm_vector_t *pshm_vect =
         shm.construct<shm_vector_t>(ip::anonymous_instance)(shm_alloc);
      pshm_vect->resize(MaxElem);
      //Initialize all the nodes
      for(int i = 0; i < MaxElem; ++i)    (*pshm_vect)[i].set(i);
      //Now create the shared memory intrusive list
      intrusive_list_t *plist = shm.construct<intrusive_list_t>(ip::anonymous_instance)();
      //Insert objects stored in shared memory vector in the intrusive list
      plist->insert(plist->end(), pshm_vect->begin(), pshm_vect->end());
      //Check all the inserted nodes
      int checker = 0;
      for( intrusive_list_t::const_iterator it = plist->begin(), itend(plist->end())
         ; it != itend; ++it, ++checker){
         if(it->get() != checker)   return false;
      }
      //Now delete the list and after that, the nodes
      shm.destroy_ptr(plist);
      shm.destroy_ptr(pshm_vect);
   }
   ip::shared_memory_object::remove(ShmName);
   return 0;
}

Не каждый умный указатель совместим сBoost.Intrusive:

  • Совместимость с C++11<std::pointer_traits>требования.Boost.Intrusiveиспользует свой собственный<pointer_traits>класс для реализации этих функций в компиляторах C++11 и C++03.
  • Он должен иметь ту же семантику владения, что и сырой указатель. Это означает, что умные указатели управления ресурсами (например,<boost::shared_ptr>) не могут быть использованы.

Преобразование из умного указателя в необработанный указатель будет осуществляться в виде рекурсивного вызова<operator->()>до тех пор, пока функция не вернет необработанный указатель.


PrevUpHomeNext

Статья Using smart pointers with Boost.Intrusive containers раздела The Boost C++ Libraries BoostBook Documentation Subset Chapter 17. Boost.Intrusive может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: Chapter 17. Boost.Intrusive ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-05-19 17:47:01/0.00677490234375/0