Skip to content

Instantly share code, notes, and snippets.

@adurpas
Created December 2, 2012 18:29
Show Gist options
  • Save adurpas/4190337 to your computer and use it in GitHub Desktop.
Save adurpas/4190337 to your computer and use it in GitHub Desktop.
// ISU laboratory session #9, exercise #2.
#include "SmartString.hpp"
SmartString::SmartString(std::string* str) : str_(str), counter_(new unsigned int(1))
{
// Comment
}
SmartString::~SmartString() // Destructor
{
--(*counter_); // Decrease counter_
if(*counter_ == 0) // Check if the last SmartString is pointing at the allocated string
{
delete str_;
delete counter_;
cout << "Destructor: string deleted!" << endl;
}
}
std::string* SmartString::get()
{
return str_;
}
string* SmartString::operator->()
{
return str_;
}
string& SmartString::operator*()
{
return *str_;
}
SmartString::SmartString(const SmartString& other) // Copy constructor
{
cout << "Copy constructor called. Pointers assignment in process...";
cout << endl;
str_ = other.str_;
counter_ = other.counter_;
++(*counter_); // Increase counter
}
SmartString& SmartString::operator=(const SmartString& other) //Assignment operator
{
cout << "Assignment operator called...";
cout << endl;
if (this != &other)
{
--(*counter_);
if (*counter_ == 0) // Check if it the last before getting a new assignment
{
delete counter_;
delete str_;
cout << "SmartString deleted" << endl;
}
counter_ = other.counter_;
++(*counter_);
str_ = other.str_;
}
return *this;
}
ostream& operator<<(ostream& os, const SmartString& ss) {
os << "The string \"" << *ss.str_ << "\" is pointed to by #" << *ss.counter_ << endl;
return os;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment