Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Last active March 23, 2019 10:30
Show Gist options
  • Save y-fedorov/2b83057c551d04e0d8749d1da728d3fb to your computer and use it in GitHub Desktop.
Save y-fedorov/2b83057c551d04e0d8749d1da728d3fb to your computer and use it in GitHub Desktop.
// Copy assignment operator implementation
#include <iostream>
#include <string>
#include <memory>
#include <algorithm>
class DataObject {
public:
DataObject(std::string_view value)
: mDataField(value) {}
void setData(std::string_view v){
mDataField = v;
}
std::string_view data(){
return mDataField;
}
private:
std::string mDataField;
};
class DemoObject {
public:
DemoObject(std::string_view string)
: mSharedObject(std::make_shared<DataObject>(string)),
mDemoValue(325),
mPointerData(new DataObject(string))
{
}
// Copy constructor
DemoObject(const DemoObject &other)
: mPointerData(new DataObject(*other.mPointerData)),
mDemoValue(other.mDemoValue),
mSharedObject(std::make_shared<DataObject>(*other.mSharedObject))
{
}
/*
// Assignment operator
DemoObject& operator=(const DemoObject &other){
if (&other == this)
return *this;
// release allocated resources
delete mPointerData;
mPointerData = new DataObject(*other.mPointerData);
mDemoValue = other.mDemoValue;
mSharedObject = std::make_shared<DataObject>(*other.mSharedObject);
return *this;
}
*/
void swap(DemoObject &other){
// because of ADL the compiler will use
// custom swap for members if it exists
// falling back to std::swap
using std::swap;
swap(mSharedObject, other.mSharedObject);
swap(mDemoValue, other.mDemoValue);
swap(mPointerData, other.mPointerData);
}
// Copy assignment operator
DemoObject& operator=(DemoObject other){
if (&other == this)
return *this;
swap(other);
return *this;
}
~DemoObject(){
delete mPointerData;
}
void setPointerObjectData(std::string_view value){
if (mPointerData){
mPointerData->setData(value);
}
}
std::string_view getPointerObjectData(){
if (mPointerData){
return mPointerData->data();
}
return nullptr;
}
private:
std::shared_ptr<DataObject> mSharedObject;
int mDemoValue;
DataObject *mPointerData;
};
int main(int argc, const char * argv[]) {
DemoObject demoObject_1("My first demo object");
DemoObject demoObject_2("My second demo object");
auto s1 = std::string(demoObject_1.getPointerObjectData());
auto s2 = std::string(demoObject_2.getPointerObjectData());
demoObject_2 = demoObject_1;
assert(!s1.compare(demoObject_2.getPointerObjectData()));
assert(s2.compare(demoObject_2.getPointerObjectData()));
demoObject_2.setPointerObjectData("new data");
assert(s1.compare(demoObject_2.getPointerObjectData()));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment