Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Created January 25, 2016 10:00
Show Gist options
  • Save y-fedorov/e8dd3fd44198521deafc to your computer and use it in GitHub Desktop.
Save y-fedorov/e8dd3fd44198521deafc to your computer and use it in GitHub Desktop.
How to copy class with pointers elegant way (http://users.livejournal.com/_winnie/32542.html?thread=164126#t164126)
//
// main.cpp
// How to copy class with pointers elegant way
// from: http://users.livejournal.com/_winnie/32542.html?thread=164126#t164126
//
// Created by Yaroslav Fedorov on 12/01/16.
// Copyright © 2016 Yaroslav Fedorov. All rights reserved.
//
#include <iostream>
#include <memory>
#include <string.h>
class B
{
public:
B( std::string name ) : mName(name) {}
inline B* clone() const
{
return new B(*this);
}
private:
std::string mName;
};
struct Bimple : std::unique_ptr<B>
{
Bimple() {}
Bimple(const Bimple &other) : std::unique_ptr<B>( other.get() ? other.get()->clone() : nullptr ){};
Bimple& operator=(Bimple const &rhs)
{
if ( this == &rhs )
return *this;
Bimple(rhs).swap(*this);
return *this;
}
};
class A
{
public:
Bimple b1, b2;
std::string s;
void swap(A &other) throw()
{
b1.swap(other.b1);
b2.swap(other.b2);
s.swap(other.s);
}
A& operator=(const A& other)
{
if ( this == &other )
return *this;
A(other).swap(*this);
return *this;
}
};
int main(int argc, const char * argv[])
{
A a1;
A a2;
a1.b1.reset(new B("b1-test"));
a1.b2.reset(new B("b2-test"));
a2 = a1;
a1 = a1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment