Standard Template Library Programmer's Guide
Здесь есть возможность читать онлайн «Standard Template Library Programmer's Guide» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, Справочники, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Standard Template Library Programmer's Guide
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
Standard Template Library Programmer's Guide: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Standard Template Library Programmer's Guide»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Standard Template Library Programmer's Guide — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Standard Template Library Programmer's Guide», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Memory Allocation
Classes
Allocators
Category: allocators
Component type: overview
Allocators encapsulate allocation and deallocation of memory. They provide a low-level interface that permits efficient allocation of many small objects; different allocator types represent different schemes for memory management.
Note that allocators simply allocate and deallocate memory, as opposed to creating and destroying objects. The STL also includes several low-level algorithms for manipulating uninitialized memory.
Note also that allocators do not attempt to encapsulate multiple memory models. The C++ language only defines a single memory model (the difference of two pointers, for example, is always ptrdiff_t ), and this memory model is the only one that allocators support. This is a major change from the definition of allocators in the original STL. [1]
The details of the allocator interface are still subject to change, and we do not guarantee that specific member functions will remain in future versions. You should think of an allocator as a "black box". That is, you may select a container's memory allocation strategy by instantiating the container template with a particular allocator [2], but you should not make any assumptions about how the container actually uses the allocator.
The available allocators are as follows. In most cases you shouldn't have to worry about the distinction: the default allocator, alloc , is usually the best choice.
alloc |
The default allocator. It is thread-safe, and usually has the best performance characteristics. |
pthread_alloc |
A thread-safe allocator that uses a different memory pool for each thread; you can only use pthread_alloc if your operating system provides pthreads. Pthread_alloc is usually faster than alloc , especially on multiprocessor systems. It can, however, cause resource fragmentation: memory deallocated in one thread is not available for use by other threads. |
single_client_alloc |
A fast but thread-unsafe allocator. In programs that only have one thread, this allocator might be faster than alloc . |
malloc_alloc |
An allocator that simply uses the standard library function malloc . It is thread-safe but slow; the main reason why you might sometimes want to use it is to get more useful information from bounds-checking or leak-detection tools while you are debugging. |
vector V(100, 5.0); // Uses the default allocator.
vector local(V.begin(), V.end());
• Allocator
• alloc
• pthread_alloc
• single_client_alloc
• malloc_alloc
• raw_storage_iterator
• construct
• destroy
• uninitialized_copy
• uninitialized_fill
• uninitialized_fill_n
• get_temporary_buffer
• return_temporary_buffer
[1] The reason for this change is that the new interface reduces memory fragmentation, and that it allows an implementation that is both efficient and thread-safe.
[2] Different containers may use different allocators. You might, for example, have some containers that use the default allocator alloc and others that use pthread_alloc . Note, however, that vector and vector are distinct types.
Functions
construct
Category: allocators
Component type: function
template
void construct(T1* p, const T2& value);
In C++, the operator new allocates memory for an object and then creates an object at that location by calling a constructor. Occasionally, however, it is useful to separate those two operations. [1] If p is a pointer to memory that has been allocated but not initialized, then construct(p, value) creates an object of type T1 at the location pointed to by p . The argument value is passed as an argument to T1 's constructor.
Defined in the standard header memory, and in the nonstandard backward-compatibility header algo.h. The construct algorithm is no longer part of the C++ standard; it was present in early drafts, and it is retained in this implementation for backward compatibility.
• T1 must have a constructor that takes a single argument of type T2 .
• p is a valid pointer that points to a region of memory whose size is at least sizeof(T1) .
• The memory pointed to by p is uninitialized. That is, no object has been constructed at the location p .
double* dp = (double*)malloc(sizeof(double));
construct(dp, 3);
assert(*dp == 3);
[1] In particular, construct , along with other low-level memory allocation primitives, is used to implement container classes.
Allocators, destroy , uninitialized_copy , uninitialized_fill , uninitialized_fill_n , raw_storage_iterator
destroy
Category: allocators
Component type: function
Destroy is an overloaded name; there are actually two destroy functions.
template
void destroy(T* pointer);
template
void destroy(ForwardIterator first, ForwardIterator last);
In C++, the operator delete destroys an object by calling its destructor, and then deallocates the memory where that object was stored. Occasionally, however, it is useful to separate those two operations. [1] Destroy calls an object's destructor without deallocating the memory where the object was stored.
The first version of destroy destroys the object pointed to by pointer by calling the destructor T::~T() . The memory pointed to by pointer is not deallocated, and can be reused for some other object.
The second version of destroy destroys all of the objects in the range of elements [first, last) . It is equivalent to calling destroy(&*i) for each iterator i in the range [first, last) .
Defined in the standard header memory, and in the nonstandard backward-compatibility header algo.h. The destroy algorithms are no longer part of the C++ standard; they were present in early drafts, and they are retained in this implementation for backward compatibility.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Standard Template Library Programmer's Guide»
Представляем Вашему вниманию похожие книги на «Standard Template Library Programmer's Guide» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Standard Template Library Programmer's Guide» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.