Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Basic MyString Move Semantics Implementation
WhatsApp
Gaurav Kumar
Sep 17
2014
1.7
k
0
0
#ifndef MYSTRING_H
#define MYSTRING_H
#include <string>
using
namespace
std;
class
MyString
{
public
:
MyString()
{
m_ptr = nullptr;
}
explicit
MyString(
const
string str)
{
m_ptr =
new
string(str);
}
MyString(
const
MyString& other)
{
if
(other.m_ptr)
m_ptr =
new
string(*other.m_ptr);
else
m_ptr = nullptr;
}
MyString(MyString&& other)
{
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
MyString& operator =(
const
MyString& other)
{
MyString(other).swap(*
this
);
return
*
this
;
}
MyString& operator =(MyString&& other)
{
MyString(move(other)).swap(*
this
);
return
*
this
;
}
~MyString()
{
delete
m_ptr;
}
string get()
const
{
return
m_ptr ? *m_ptr : 0;
}
void
swap(MyString& other)
{
std::swap(
m_ptr, other.m_ptr);
}
private
:
std::string *m_ptr;
};
#endif // MYSTRING_H
c++11
copy constructor
move constructor
move semantics
Up Next
Basic MyString Move Semantics Implementation