13.44 + 13.47
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
#include<vector>
#include<forward_list>
#include<deque>
#include<algorithm>
#include<list>
#include<functional>
#include<iterator>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<cctype>
#include<memory>
#include<new>
#include<utility>
using namespace std;
using namespace placeholders;
//动态内存管理
class String
{
public:
String();
String(const char* s)
{
auto s1 = const_cast<char*>(s);
while (*s1)
{
++s1;
}
alloc_n_copy(s, s1);
}
String(const String&);
String& operator=(const String&);
~String()
{
free();
}
void free()
{
if (elements)
{
for_each(elements, end, [this](char& rhs) {alloc.destroy(&rhs); });
alloc.deallocate(elements, end - elements);
}
}
private:
static allocator<char> alloc;
char* elements;
char* end;
pair<char*, char*> alloc_n_copy(const char* a, const char* b)
{
auto s1 = alloc.allocate(b - a);
auto s2 = uninitialized_copy(a, b, s1);
return make_pair(s1, s2);
}
void range_initializer(const char* c, const char* d)
{
auto p = alloc_n_copy(d, c);
elements = p.first;
end = p.second;
}
};
String::String(const String& rhs)
{
range_initializer(rhs.elements, rhs.end);
cout << "拷贝构造函数" << end;
}
String& String::operator=(const String& rhs)
{
auto new_str = alloc_n_copy(rhs.elements, rhs.end);
free();
elements = new_str.first;
end = new_str.second;
cout << "拷贝赋值运算符" << endl;
return *this;
}
int main(int argc, char** argv)
{
int&& rr1 = 42;
int&& rr2 = std::move(rr1);
cin.get();
}
这篇博客探讨了C++中动态内存管理的实现,通过一个自定义的String类展示了如何使用智能指针和内存分配器进行对象的拷贝构造和赋值操作。内容涵盖了动态内存分配、拷贝构造函数和拷贝赋值运算符的细节。
1万+

被折叠的 条评论
为什么被折叠?



