#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <vector>
using std::vector;
#include <string>
using std::string;
#include<algorithm>
#include"HasPtr.h"
//#include"ex13_31.h"
int main(int argc, char *argv[])
{
cout << "start" << endl;
vector<HasPtr> v;
v.reserve(10);
v.emplace_back("one");
v.emplace_back("two");
v.emplace_back("three");
v.emplace_back("four");
v.emplace_back("five");
v.emplace_back("six");
v.emplace_back("seven");
v.emplace_back("eight");
v.emplace_back("nine");
v.emplace_back("ten");
//test swap
cout << "\n swap \n";
swap(v[0], v[1]);
cout << "\n std::swap \n";
std::swap(v[0], v[1]);
//test std::sort
cout << endl << "\n Sort Start \n";
//using std::swap;
std::sort(v.begin(), v.end());
cout << "\n Sort Ends \n";
cout << "\n end \n";
return EXIT_SUCCESS;
}
#pragma once
#include<string>
using std::string;
#include<iostream>
class HasPtr
{
public:
friend void swap(HasPtr& lhs, HasPtr& rhs);
friend bool operator<(const HasPtr&, const HasPtr&);
HasPtr()=delete;
//HasPtr(HasPtr&& original)=delete;
//HasPtr& operator=(HasPtr&&)=delete;
HasPtr(const string& s = string()) :
ps(new string(s)), i(0),
use(new size_t(1))
{
std::cout << "Construct new HasPtr " << s << std::endl;
}
HasPtr(const HasPtr& original) :
ps(new string(*original.ps)), i(original.i),
use(original.use)
{
++(*use);
std::cout << "Construct copy HasPtr with " << *ps << std::endl;
}
~HasPtr();
HasPtr& operator=(const HasPtr&);
private:
string* ps{};
int i{};
size_t* use{};
};
void swap(HasPtr& lhs, HasPtr& rhs);
bool operator<(const HasPtr&, const HasPtr&);
#include "HasPtr.h"
HasPtr::~HasPtr()
{
std::cout << "Destruct HasPtr with " << *ps << std::endl;
--(*use);
if (use == 0)
{
delete ps;
delete use;
}
}
HasPtr& HasPtr::operator=(const HasPtr& other)
{
std::cout << *ps << " = " << *other.ps << std::endl;
++(*other.use);
--(*use);
if (use == 0)
{
delete ps;
delete use;
}
ps = other.ps;
i = other.i;
use = other.use;
return *this;
}
void swap(HasPtr& lhs, HasPtr& rhs)
{
std::cout << "swap " << *lhs.ps << " with " << *rhs.ps << std::endl;
//using std::swap;
swap(lhs.ps, rhs.ps);
std::swap(lhs.i, rhs.i);
std::swap(lhs.use, rhs.use);
}
bool operator<(const HasPtr& lhs, const HasPtr& rhs)
{
return *lhs.ps < *rhs.ps;
}