unique_ptr / auto_ptr выглядит одинаково с пользовательским удалением для c ++ 98

auto_ptr не поддерживает настраиваемое средство удаления, и tr1 shared_ptr мне не подходит.
Существуют ли какие-либо хорошие варианты до c11 для unique_ptr / auto_ptr, похожие на настраиваемый средство удаления?


person Peretz Levinov    schedule 15.09.2018    source источник
comment
Использовать реализации библиотеки boost?   -  person UnholySheep    schedule 15.09.2018
comment
моя версия повышения - 1.33.1. У меня boost / scoped_ptr нет удаления, и я не могу скомпилировать с ‹boost / interprocess / smart_ptr / scoped_ptr.hpp›. boost unique_ptr из версии 1.57   -  person Peretz Levinov    schedule 15.09.2018
comment
Под c11 вы имеете в виду C++11?   -  person Galik    schedule 15.09.2018
comment
@PeretzLevinov есть что-то, что мешает вам перейти на Boost 1.57 (или новее)?   -  person dfrib    schedule 15.09.2018
comment
Почему вы используете компилятор до C ++ 11? Это связано с ограничением платформы ОС, которую вы используете, или это ограничение проекта? Кстати, вы никогда не должны использовать auto_ptr, который теперь устарел.   -  person ADG    schedule 15.09.2018


Ответы (1)


Boost.Move: unique_ptr (C ++ 03, Boost 1.57)

Реализация unique_ptr без семантики перемещения C ++ 11 (и выше) немного сложна, но если бы вы могли эмулировать семантику перемещения, вы могли бы пойти дальше с реализацией семантики, аналогичной семантике _ 2_.

Boost предоставил эту реализацию для C ++ 03 как часть библиотеки Boost.Move:

Что такое Boost.Move?

Ссылки Rvalue - это основная функция C ++ 0x, обеспечивающая семантику перемещения для значений C ++. Однако нам не нужны компиляторы C ++ 0x, чтобы воспользоваться преимуществами семанатики перемещения. Boost.Move эмулирует семантику перемещения C ++ 0x в компиляторах C ++ 03 и позволяет писать переносимый код, который оптимально работает в компиляторах C ++ 03 и C ++ 0x.

В частности, от Boost 1.57 и выше, обеспечивая boost/move/unique_ptr.hpp

//!\file
//! Describes the smart pointer unique_ptr, a drop-in replacement for std::unique_ptr,
//! usable also from C++03 compilers.
//!
//! Main differences from std::unique_ptr to avoid heavy dependencies,
//! specially in C++03 compilers:
//!   - <tt>operator < </tt> uses pointer <tt>operator < </tt>instead of <tt>std::less<common_type></tt>. 
//!      This avoids dependencies on <tt>std::common_type</tt> and <tt>std::less</tt>
//!      (<tt><type_traits>/<functional></tt> headers. In C++03 this avoid pulling Boost.Typeof and other
//!      cascading dependencies. As in all Boost platforms <tt>operator <</tt> on raw pointers and
//!      other smart pointers provides strict weak ordering in practice this should not be a problem for users.
//!   - assignable from literal 0 for compilers without nullptr
//!   - <tt>unique_ptr<T[]></tt> is constructible and assignable from <tt>unique_ptr<U[]></tt> if
//!      cv-less T and cv-less U are the same type and T is more CV qualified than U.

что позволяет предоставить unique_ptr связанное средство удаления, отличное от установленного по умолчанию:

//! A unique pointer is an object that owns another object and
//! manages that other object through a pointer.
//! 
//! ...
//!
//! \tparam T Provides the type of the stored pointer.
//! \tparam D The deleter type:
//!   -  The default type for the template parameter D is default_delete. A client-supplied template argument
//!      D shall be a function object type, lvalue-reference to function, or lvalue-reference to function object type
//!      for which, given a value d of type D and a value ptr of type unique_ptr<T, D>::pointer, the expression
//!      d(ptr) is valid and has the effect of disposing of the pointer as appropriate for that deleter.
//!   -  If the deleter's type D is not a reference type, D shall satisfy the requirements of Destructible.
//!   -  If the type <tt>remove_reference<D>::type::pointer</tt> exists, it shall satisfy the requirements of NullablePointer.
template <class T, class D = default_delete<T> >
class unique_ptr
{
    /* ... */
}
person dfrib    schedule 15.09.2018