Overview
uninitialized memory algorithms enable populating objects in uninitialized memory. They construct the objects in-place, This allows to obtain fully constructed copies of the elements into a range of uninitialized memory, such as a memory block obtained by a call to malloc.
Details
Name | Description |
---|---|
ForwardIterator uninitialized_copy ( InputIterator first, InputIterator last, ForwardIterator target) | Copies and constructs the elements in the range [first,last] into the uninitialized memory target. Example const char *numbers[] = {"one", "two", "three", "four"}; size_t sz = sizeof(numbers)/sizeof(const char *); char *buf = new char[sizeof(string)*sz]; string *sbuf = reinterpret_cast<string*>(buf); auto last = std::uninitialized_copy ( numbers, numbers+sz, sbuf ); //prints one two three four for (auto itr = sbuf; itr != last; ++itr) std::cout << *itr << " "; for (auto itr = sbuf; itr != last; ++itr) itr->~string(); delete[] buf; |
ForwardIterator uninitialized_copy_n ( InputIterator first, size_t n, ForwardIterator result) | Same as uninitialized_copy except n number of elements are copied. Examples: const char *numbers[] = {"one", "two", "three", "four"}; size_t sz = sizeof(numbers)/sizeof(const char *); char *buf = new char[sizeof(string)*sz]; string *sbuf = reinterpret_cast<string*>(buf); auto last = std::uninitialized_copy_n ( numbers, sz, sbuf ); //prints one two three four for (auto itr = sbuf; itr != last; ++itr) std::cout << *itr << " "; for (auto itr = sbuf; itr != last; ++itr) itr->~string(); delete[] buf; |
ForwardIterator uninitialized_fill ( InputIterator first, InputIterator last, const T& x) | Constructs the elements into the uninitialized memory range [first,last] and populates them using x. Examples: size_t sz = 4; char *buf = new char[sizeof(string)*sz]; string *sbuf = reinterpret_cast<string*>(buf); std::uninitialized_fill ( sbuf, sbuf+sz, "veda"); //prints veda veda veda veda for (auto itr = sbuf; itr != (sbuf+sz); ++itr) std::cout << *itr << " "; for (auto itr = sbuf; itr != (sbuf+sz); ++itr) itr->~string(); delete[] buf; |
ForwardIterator uninitialized_fill_n ( InputIterator first, size_t n, const T& x) | Same as uninitialized_fill except n number of elements are filled. Examples: size_t sz = 4; char *buf = new char[sizeof(string)*sz]; string *sbuf = reinterpret_cast<string*>(buf); std::uninitialized_fill_n ( sbuf, sz, "veda"); //prints veda veda veda veda for (auto itr = sbuf; itr != (sbuf+sz); ++itr) std::cout << *itr << " "; for (auto itr = sbuf; itr != (sbuf+sz); ++itr) itr->~string(); delete[] buf; |
The example depicts the usage.
No comments:
Post a Comment