rval-references-examples.cpp [plain text]
template<typename T>
class unique_ptr {
T *ptr;
unique_ptr(const unique_ptr&) = delete; unique_ptr &operator=(const unique_ptr&) = delete; public:
unique_ptr() : ptr(0) { }
unique_ptr(unique_ptr &&other) : ptr(other.ptr) { other.ptr = 0; }
explicit unique_ptr(T *ptr) : ptr(ptr) { }
~unique_ptr() { delete ptr; }
unique_ptr &operator=(unique_ptr &&other) { if (this == &other)
return *this;
delete ptr;
ptr = other.ptr;
other.ptr = 0;
return *this;
}
};
template<typename T>
struct remove_reference {
typedef T type;
};
template<typename T>
struct remove_reference<T&> {
typedef T type;
};
template<typename T>
struct remove_reference<T&&> {
typedef T type;
};
template <class T> typename remove_reference<T>::type&& move(T&& t) {
return static_cast<typename remove_reference<T>::type&&>(t);
}
template <class T> T&& forward(typename remove_reference<T>::type& t) {
return static_cast<T&&>(t);
}
template <class T> T&& forward(typename remove_reference<T>::type&& t) {
return static_cast<T&&>(t);
}
template<typename T, typename ...Args>
unique_ptr<T> make_unique_ptr(Args &&...args) {
return unique_ptr<T>(new T(forward<Args>(args)...));
}
template<typename T> void accept_unique_ptr(unique_ptr<T>);
unique_ptr<int> test_unique_ptr() {
unique_ptr<int> p;
unique_ptr<int> p1(new int);
unique_ptr<int> p2(make_unique_ptr<int>(17));
unique_ptr<int> p3 = make_unique_ptr<int>(17);
unique_ptr<int> p4(p); unique_ptr<int> p5 = p;
p2 = move(p);
p2 = make_unique_ptr<int>(0);
p2 = p3;
accept_unique_ptr(make_unique_ptr<double>(0.0));
accept_unique_ptr(move(p2));
accept_unique_ptr(p);
return p;
}
namespace perfect_forwarding {
struct A { };
struct F0 {
void operator()(A&, const A&, A&&, const A&&, A&&, const A&&); };
template<typename F, typename ...Args>
void forward(F f, Args &&...args) {
f(static_cast<Args&&>(args)...); }
template<typename T> T get();
void test_forward() {
forward(F0(), get<A&>(), get<A const&>(), get<A>(), get<const A>(),
get<A&&>(), get<const A&&>());
forward(F0(), get<A&>(), get<A const&>(), get<A>(), get<const A>(), get<const A&&>(), get<const A&&>());
}
};