#include <list>
#include <iostream>
#include <chrono>
#include <cstring>
using namespace std;
struct Foo
{
int size{ 0 };
double* a{nullptr};
Foo()
{
cout << "default\n";
size = 1e8;
a = new double[size];
for (int i = 0; i < size; i++) {
a[i] = double(i) / 0.2 * 3. + 5.;
}
}
Foo(const Foo& f)
{
cout << "copy\n";
if (a != nullptr) {
delete[] a;
size = 0;
}
if (f.size != 0)
{
a = new double[f.size];
size = f.size;
std::memcpy(a, f.a, size * sizeof(double));
}
}
Foo& operator=(const Foo& f)
{
cout << "copy=\n";
if (a != nullptr)
{
delete[] a;
size = 0;
}
if (f.size != 0)
{
a = new double[f.size];
size = f.size;
std::memcpy(a, f.a, size * sizeof(double));
}
return *this;
}
Foo(Foo&& f) noexcept
{
cout << "move\n";
a = f.a;
size = f.size;
f.size = 0;
f.a = nullptr;
}
Foo& operator=(Foo&& f) noexcept
{
cout << "move=\n";
a = f.a;
size = f.size;
f.size = 0;
f.a = nullptr;
return *this;
}
~Foo()
{
if (a != nullptr) {
delete[] a;
}
}
};
struct S2
{
std::list<Foo> foo2;
void appendCopy(const Foo& f)
{
foo2.push_back(f);
}
void appendMove(Foo&& f)
{
foo2.push_back(std::move(f));
}
};
struct S {
std::list<Foo> foo1;
void funcCopy(S2& s2)
{
auto start = chrono::steady_clock::now();
for (const auto& f : foo1)
s2.appendCopy(f);
auto end = chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<chrono::microseconds>(end - start);
cout << "copy time: " << duration.count() << endl;
}
void funcMove(S2 s2) {
auto start = chrono::steady_clock::now();
for (auto&& f : foo1)
s2.appendMove(std::move(f));
auto end = chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<chrono::microseconds>(end - start);
cout << "move time: " << duration.count() << endl;
}
};
int main()
{
S s;
S2 s1, s2;
s.foo1 = { Foo{}, Foo{} };
s.funcCopy(s1);
s.funcMove(s2);
}