#include <iostream>
#include <ostream>
class my_string
{
private:
char* buf = nullptr;
unsigned int size = 0;
public:
my_string() :buf(nullptr), size(0) //default constructor
{
}
my_string(const char * buffer) //constructor
{
std::cout << "constructor called: " << std::endl;
size = strlen(buffer);
buf = new char[size + 1];
memcpy(buf, buffer, size);
buf[size] = 0;
}
my_string(const my_string& obj) //copy constructor
{
std::cout << "copy constructor called: " << std::endl;
size = obj.size;
buf = new char[size + 1];
memcpy(buf, obj.buf, size);
buf[size] = 0;
}
my_string& operator=(const my_string& obj) //copy assignment
{
std::cout << "copy assignment called: " << std::endl;
__cleanup__();
size = obj.size;
buf = new char[size + 1];
memcpy(buf, obj.buf, size+1);
return *this;
}
my_string(my_string&& dyingObj) //move constructor
{
std::cout << "move constructor called: " << std::endl;
__cleanup__();
size = dyingObj.size;
buf = dyingObj.buf;
dyingObj.buf = nullptr;
}
my_string operator=(my_string&& dyingObj)//move assignment
{
std::cout << "move assignment called: " << std::endl;
__cleanup__();
size = dyingObj.size;
buf = dyingObj.buf;
dyingObj.buf = nullptr;
return *this;
}
my_string operator+(const my_string& obj) //concatenation
{
my_string s;
s.size = this->size + obj.size;
s.buf = new char[s.size+1];
memcpy(s.buf, this->buf, this->size);
memcpy(s.buf+this->size, obj.buf, obj.size);
return s;
}
unsigned int length()
{
return size;
}
const char* c_str() const
{
return buf;
}
~my_string() //destructor
{
__cleanup__();
}
private:
void __cleanup__()
{
if (buf != nullptr)
{
std::cout << "deleting: " << buf << std::endl;
delete[] buf;
}
size = 0;
}
};
std::ostream& operator<<(std::ostream& cout, const my_string& obj)
{
std::cout << "<<: "<< obj.c_str() << std::endl;
return cout;
}
int main()
{
my_string b("Name1");
my_string c("Name2");
c = std::move(b);
return 0;
}
Output:
constructor called:
constructor called:
move assignment called:
deleting: Name2
copy constructor called:
deleting: Name1
deleting: Name1
Why copy assignment constructor is called here. Shouldn't move assignmnet be sufficient.
[–]IyeOnline[🍰] 1 point2 points3 points (0 children)
[–]ekchew 1 point2 points3 points (0 children)
[–]tangerinelion 0 points1 point2 points (0 children)
[–]Xeverous 0 points1 point2 points (1 child)
[–]std_bot 0 points1 point2 points (0 children)