Skip to content

Instantly share code, notes, and snippets.

@KellenSunderland
Last active January 13, 2019 17:11
Show Gist options
  • Save KellenSunderland/d431119580a116410c672b9535d85170 to your computer and use it in GitHub Desktop.
Save KellenSunderland/d431119580a116410c672b9535d85170 to your computer and use it in GitHub Desktop.
rvalue test
#include <iostream>
#include <utility>
#include <vector>
#include <cstring>
using namespace std;
class MyType {
public:
MyType() {
std::cerr<<"default ctor called"<<std::endl;
pointer_ = new int;
*pointer_ = 1;
memset(array_, 0, sizeof(array_));
vector_.push_back(3.14);
}
MyType(MyType&& other) noexcept : pointer_(nullptr) {
std::cerr<<"move ctor called"<<std::endl;
delete pointer_;
pointer_ = other.pointer_;
other.pointer_ = nullptr;
// Copy the contents of the array.
memcpy(array_, other.array_, sizeof(array_));
// Swap with our vector. Leaves the old contents in |other|.
// We could destroy the old content instead, but this is equally
// valid.
vector_.swap(other.vector_);
std::cerr<<"move ctor complete"<<std::endl;
}
MyType(const MyType& other) {
std::cerr<<"copy ctor called"<<std::endl;
// Copy memory.
pointer_ = new int;
*pointer_ = *other.pointer_;
std::cerr<<"expensive memcopies happening"<<std::endl;
memcpy(array_, other.array_, sizeof(array_));
vector_ = other.vector_;
std::cerr<<"copy ctor complete"<<std::endl;
}
unsigned long Size(){
return vector_.size();
}
~MyType() {
delete pointer_;
}
private:
int* pointer_;
char array_[42]{};
std::vector<float> vector_;
};
class MyObjectB {
public:
void DoSomething(MyType spot) {
if (spot.Size() > 1000) {
// do something
std::cout<<"large size"<<std::endl;
}
}
};
int main() {
auto a = MyType();
auto b = MyObjectB();
// Passing a by value, copy constructor called
b.DoSomething(a);
// Passing a by value, move constructor called
b.DoSomething(std::move(a));
}
default ctor called
copy ctor called
expensive memcopies happening
copy ctor complete
move ctor called
move ctor complete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment