이동생성자(Move Constructor)
Last updated
Last updated
#ifndef _VECF_H_
#define _VECF_H_
#include <cstring>
#include <iostream>
using namespace std;
class VecF
{
int n;
float* arr;
public:
// 생성자
VecF(int d, const float* a = nullptr) : n{ d } {
arr = new float[d];
if (a) {
memcpy(arr, a, sizeof(float)* n);
}
}
// 복사생성자
VecF(const VecF& ref) : n{ref.n} {
arr = new float[n];
memccpy(arr, ref.arr, sizeof(float) * n);
}
// 소멸자
~VecF() {
delete[] arr;
}
// 두 벡터를 더해 반환
VecF add(const VecF& fv) const {
VecF tmp(n);
for (int i = 0; i < n; i++) {
tmp.arr[i] = arr[i] + fv.arr[i];
}
return tmp;
}
// 출력
void print() const {
cout << "[ ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << "]" << endl;
}
};
#endif // !_VECF_H_VecF v1(3), v2(3);
VecF& vLRef = v1; // lvalue 참조
int& a = 10; // 오류
const int& b = 20; // 상수 lvalue로 rvalue 참조
int&& c = 30; // rvalue 참조
VecF&& vRRef1 = v1.add(v2);
VecF&& vRRef2 = v2; // 오류 rvalue참조로 lvalue를 참조할수 없음class ClassName {
...
public:
ClassName(ClassName&& obj) {
...
}
}VecF(VecF&& obj) : n{obj.n}, arr{obj.arr} {
obj.arr = nullptr;
obj.n = 0;
}