当一个新的容器被定义在一个std::array
#include <iostream>
#include <array>
#include <initializer_list>
// My container
template<typename Type, unsigned int Size>
class MyContainer
{
// Lifecycle
public:
MyContainer() : _data() {}
MyContainer(const MyContainer<Type, Size>& rhs) : _data(rhs.data()) {}
MyContainer(const std::array<Type, Size>& rhs) : _data(rhs) {}
template<typename... Types> MyContainer(const Types&... numbers) : _data({{numbers...}}) {}
~MyContainer() {}
// Assignment
public:
MyContainer<Type, Size>& operator=(const MyContainer<Type, Size>& rhs) {_data = rhs.data(); return *this}
// Accessors
public:
Type& operator[](const unsigned int i) {return _data[i];}
const Type& operator[](const unsigned int i) const {return _data[i];}
std::array<Type, Size>& data() {return _data;}
const std::array<Type, Size>& data() const {return _data;}
// Operators
public:
MyContainer<Type, Size> operator+(const MyContainer<Type, Size>& rhs)
{
MyContainer<Type, Size> result;
for (unsigned int i = 0; i < Size; ++i) {
result[i] = _data[i] + rhs[i];
}
return result;
}
// Data members
protected:
std::array<Type, Size> _data;
};
// Main
int main(int argc, char* argv[])
{
// Initialization
MyContainer<double, 4> x = {0., 1., 2., 3.};
MyContainer<double, 4> y = {4., 5., 6., 7.};
MyContainer<double, 4> z;
// Operation
z = x+y; // Can move semantics help here ?
// Result
std::cout<<z[0]<<" "<<z[1]<<" "<<z[2]<<" "<<z[3]<<std::endl;
return 0;
}
移动语义可以通过避免一些副本来加速 main() 中的操作吗?
如果答案是肯定的,如何在当前设计中实现它?