Skip to content

Commit

Permalink
Update ex13_44_47.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooophy committed Jun 28, 2015
1 parent 8b16911 commit f7f4761
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions ch13/ex13_44_47.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,54 +2,53 @@
#include <algorithm>
#include <iostream>

std::pair<char*, char*>
std::pair<char*, char*>
String::alloc_n_copy(const char *b, const char *e)
{
auto str = alloc.allocate(e-b);
return{ str, std::uninitialized_copy(b, e, str)};
auto str = alloc.allocate(e - b);
return{ str, std::uninitialized_copy(b, e, str) };
}

void String::range_initializer(const char *first, const char *last)
{
auto newstr = alloc_n_copy(first, last);
elements = newstr.first;
end = newstr.second;
auto newstr = alloc_n_copy(first, last);
elements = newstr.first;
end = newstr.second;
}

String::String(const char *s)
{
char *sl = const_cast<char*>(s);
while (*sl)
++sl;
range_initializer(s, ++sl);
char *sl = const_cast<char*>(s);
while (*sl)
++sl;
range_initializer(s, ++sl);
}

String::String(const String& rhs)
{
range_initializer(rhs.elements, rhs.end);
range_initializer(rhs.elements, rhs.end);
std::cout << "copy constructor" << std::endl;
}

void String::free()
{
if (elements) {
std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); });
alloc.deallocate(elements, end - elements);
}
if (elements) {
std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); });
alloc.deallocate(elements, end - elements);
}
}

String::~String()
{
free();
free();
}

String& String::operator = (const String &rhs)
{
auto newstr = alloc_n_copy(rhs.elements, rhs.end);
free();
elements = newstr.first;
end = newstr.second;
auto newstr = alloc_n_copy(rhs.elements, rhs.end);
free();
elements = newstr.first;
end = newstr.second;
std::cout << "copy-assignment" << std::endl;
return *this;
return *this;
}

0 comments on commit f7f4761

Please sign in to comment.