Merhabalar, "Copy & Swap idiom" u araştırıyorum. Bu kodda
#include <iostream>
#include <utility> // std::swap since C++11 (if pre C++11 use <algorithm>)
class MyClass {
public:
MyClass() = default; // Use compiler generated default constructor
MyClass(int ax, int ay, int az)
: x(ax), y(ay), z(az)
{}
MyClass(const MyClass & rhs) = default; // Use compiler generated copy ctor.
// Copy & Swap idiom
MyClass& operator= (MyClass copy) {
using std::swap;
swap(*this, copy);
return *this;
}
friend void swap(MyClass& lhs, MyClass& rhs) {
using std::swap;
swap(lhs.x, rhs.x);
swap(lhs.y, rhs.y);
swap(lhs.z, rhs.z);
}
friend std::ostream& operator<<(std::ostream& os, const MyClass& rhs) {
os << "(" << rhs.x << ", " << rhs.y << ", " << rhs.z << ")";
return os;
}
private:
int x = 0;
int y = 0;
int z = 0;
};
int main() {
MyClass o1(10, 20, 30);
std::cout << "This is my class: " << o1 << std::endl;
MyClass o2(40, 50, 60);
o2 = o1;
std::cout << "This is o2 after assignment: " << o2 << std::endl<<o1;
}
'swap ' fonksiyonunun neden "friend" tanımlandığını anlayamadım.
Bir de 'assignment operator''ü aşırı override ederken swap kullanıyoruz. Ama eğer burada pointer veya reference ile kullandığımız zaman değerleri eşitlemek yerine doğal olarak değiştiriyor. O halde bu yapı pointer veya reference işin içine girdiği zaman ölüyor mu ?
İyi Çalışmalar.
--
[ Bu gönderi, http://ddili.org/forum'dan dönüştürülmüştür. ]