当前位置:网站首页>Strvec class mobile copy
Strvec class mobile copy
2022-06-12 08:04:00 【jackniu123】
StrVec It's right vector Imitation of .string Continuously store... In memory , When there is not enough memory , Request twice the memory space , And make use of string For transfer .
Who are the members
class StrVec
{
public:
StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {
}
StrVec(const StrVec&);
StrVec(StrVec&& s)noexcept;
StrVec& operator=(StrVec&& rhs);
StrVec& operator=(const StrVec&);
~StrVec();
void push_back(const string&);
size_t size() const {
return first_free - elements; }
size_t capacity() const {
return cap - elements; }
string* begin() const {
return elements; }
string* end() const {
return first_free; }
private:
static allocator<string> alloc;
string* elements;// Head pointer
string* first_free;// Using the trailing pointer of memory
string* cap;// Array trailing pointer
void free(); // Destroy elements and free memory
void reallocate(); // Get more memory and copy existing elements
// Used by the function to which the element is added
void chk_n_alloc();
// Tool function , Copied constructor 、 Assignment operator 、 Destructors use
pair<string*, string*> alloc_n_copy(const string*, const string*);
};
Analyze one by one
Data member
- Static members allocator: Responsible for applying for memory space .allocator Class is used to separate memory request from object initialization .STL Regular use allocator Class dynamically applies for memory .allocate Can be regarded as malloc Encapsulation , deallocate Can be regarded as free( No new and delete), construct Consider calling the constructor manually ,deallocate It can be seen as a manual call to the destructor . After the memory is allocated, it can be regarded as StrVec There is a dynamic array inside the class .
string* p = new string[10]; Actually, I did two jobs : Apply for ten with the operating system string Size of memory space , Then perform default initialization on it —— That is, run the default constructor . and alloc.allocate(10) Just apply for memory space , There is no initialization process .
- Three pointers .elements, first_free, cap First pointer in turn , Tail pointer , Pointer to the last position in memory space .
Copy control
- Default structure : All three pointers are set to null .
- Copy structure : Allocate memory space of equal size first , And then use it unitialize_copy Method completes initialization in one time .
- Mobile construction : Allocate memory space of equal size first , Then set the three pointers to rhs Value . Pay attention to rhs Assigned to a destructible state .
- Copy operator : Copy and copy to ensure exceptional security . The rest are the same as the copy structure .
- Move copy operator overload : Use the method of comparing and excluding self assignment first , The rest are the same as the mobile structure .
- Destructor : Release allocator Of memory space .
Tool function
- free: It's actually a destructor .
- alloc_n_copy: Function extraction of copy construction . Returns the first and last pointers .
- chk_n_copy: Determine whether the memory space is larger .
- reallocate: Call this function when more space is needed . Apply for memory space first , Call again string Mobile copy of , Not available here unintial_copy.
Code
#include <iostream>
#include <algorithm>
#include <utility>
#include <memory>
#include <string>
using namespace std;
class StrVec
{
public:
StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {
}
StrVec(const StrVec&);
StrVec(StrVec&& s)noexcept;
StrVec& operator=(StrVec&& rhs);
StrVec& operator=(const StrVec&);
~StrVec();
void push_back(const string&);
size_t size() const {
return first_free - elements; }
size_t capacity() const {
return cap - elements; }
string* begin() const {
return elements; }
string* end() const {
return first_free; }
private:
static allocator<string> alloc;
string* elements;// Head pointer
string* first_free;// Using the trailing pointer of memory
string* cap;// Array trailing pointer
void free(); // Destroy elements and free memory
void reallocate(); // Get more memory and copy existing elements
// Used by the function to which the element is added
void chk_n_alloc();
// Tool function , Copied constructor 、 Assignment operator 、 Destructors use
pair<string*, string*> alloc_n_copy(const string*, const string*);
};
void StrVec::chk_n_alloc()
{
if (size() == capacity())
reallocate();
}
void StrVec::push_back(const string& s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
pair<string*, string*> StrVec::alloc_n_copy(const string* b, const string* e)
{
// Allocate space to hold elements in a given range
auto data = alloc.allocate(e - b);
// Initialize and return a pair
return {
data, uninitialized_copy(b, e, data) };
}
void StrVec::free()
{
if (elements)
{
for_each(elements, first_free, [this](string* rhs) {
this->alloc.destroy(rhs); });
// for (auto p = first_free; p != elements; )
// alloc.destroy(--p);
}
alloc.deallocate(elements, capacity());
}
StrVec::StrVec(const StrVec& s)
{
auto newdata = alloc_n_copy(s.begin(), s.end());
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator=(const StrVec& rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
cap = first_free = data.second;
return *this;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
auto newdata = alloc.allocate(newcapacity);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); i++)
{
alloc.construct(dest++, move(*elements++));
}
free();
elements = newdata;
first_free = dest;
cap = elements + newcapacity;
}
StrVec::StrVec(StrVec&& s)noexcept
:elements(s.elements), first_free(s.first_free), cap(s.cap)
{
s.cap = s.first_free = s.elements = nullptr;
}
StrVec& StrVec::operator=(StrVec&& rhs)
{
if (this != &rhs)
{
free();
elements = rhs.elements;
cap = rhs.cap;
first_free = rhs.first_free;
rhs.first_free = rhs.elements = rhs.cap = nullptr;
}
return *this;
}
int main()
{
}
边栏推荐
- Leetcode notes: Weekly contest 296
- 802.11 protocol: wireless LAN protocol
- Topic 1 Single_ Cell_ analysis(4)
- Mathematical Essays: Notes on the angle between vectors in high dimensional space
- Explanation and explanation on the situation that the volume GPU util (GPU utilization) is very low and the memory ueage (memory occupation) is very high during the training of pytoch
- Solve the problem of uploading sftporg apache. commons. net. MalformedServerReplyException: Could not parse respon
- Leetcode notes: Weekly contest 295
- Explain the basic working principle of Ethernet
- Servlet advanced
- StrVec类 移动拷贝
猜你喜欢

Explanation and explanation on the situation that the volume GPU util (GPU utilization) is very low and the memory ueage (memory occupation) is very high during the training of pytoch

Mathematical knowledge - derivation - Basic derivation knowledge

Classic paper review: palette based photo retrieval

Windows10 configuration database

Discrete chapter I

Getting started with Jetson nano Series IV: common skills of NVIDIA Jetson nano
![[RedisTemplate方法详解]](/img/ef/66d8e3fe998d9a788170016495cb10.png)
[RedisTemplate方法详解]

Cookies and sessions

DUF:Deep Video Super-Resolution Network Using Dynamic Upsampling Filters ...阅读笔记

L'effet de l'oie sauvage sur l'économie numérique verte de Guilin
随机推荐
Topic 1 Single_Cell_analysis(4)
Alibaba cloud deploys VMware and reports an error
AJ project: online bank project summary
Compiling principle on computer -- functional drawing language (IV): semantic analyzer
The project file contains toolsversion= "14.0". This toolset may be unknown or missing workarounds
Compiling principle on computer -- function drawing language (III): parser
Multithread decompression of tar
Discrete chapter I
Xiaomi mobile phone recording data set software operation
Introduction to coco dataset
Detailed explanation of Google open source sfmlearner paper combining in-depth learning slam -unsupervised learning of depth and ego motion from video
20220524 backbone deep learning network framework
Improvement of hash function based on life game (continued 1)
The R language uses the sample The split function divides the machine learning data set into training set and test set
Vins technical route and code explanation
Leetcode notes: biweekly contest 71
MFC中窗口刷新函数详解
Explanation and explanation on the situation that the volume GPU util (GPU utilization) is very low and the memory ueage (memory occupation) is very high during the training of pytoch
Debug debugging cmake code under clion, including debugging process under ROS environment
Final review of Discrete Mathematics (predicate logic, set, relation, function, graph, Euler graph and Hamiltonian graph)