J
Jonathan Lee
Hi all,
I want to begin using move semantics in my code assuming
only the current standard. I thought I could provide move
constructors and assignments by typedef-ing rvalue references
to "moveType" when C++0x is available, and otherwise using
a proxy "movable" class. Just to make the transition easier.
Example below.
Any thoughts?
--Jonathan
// begin: movetest.cpp
#include <cstddef>
#include <algorithm>
#if (__cplusplus > 199711L)
// Use the C++0x std::move if available
#include <utility>
namespace cpp0x = std;
#else
// Older versions of C++ use proxy class
namespace cpp0x {
template<class T>
class movable : public T {
public:
movable(T& t):T() { T::swap(t); }
};
template<class T>
movable<T> move(T& t) {
// rely on RVO
return movable<T>(t); }
}
#endif
class dummy {
char* ptr;
std::size_t len;
public:
#if (__cplusplus > 199711L) /* c++0x */
typedef dummy&& moveType;
#else
typedef cpp0x::movable<dummy>& moveType;
#endif
dummy(): ptr(0), len(0)
{ }
dummy(std::size_t n)tr(n ? new char[n] : 0), len(n)
{ }
dummy(const dummy& d)tr(d.len ? new char[d.len] : 0), len(d.len)
{ }
dummy(moveType d)tr(d.ptr), len(d.len) {
d.ptr = 0, d.len = 0;
}
dummy& operator=(moveType d) {
d.swap(*this);
return *this;
}
void swap(dummy& d) {
std::swap(ptr, d.ptr);
std::swap(len, d.len);
}
};
int main () {
dummy a(5);
dummy b;
b = cpp0x::move(a);
return 0;
}
// end: movetest.cpp
I want to begin using move semantics in my code assuming
only the current standard. I thought I could provide move
constructors and assignments by typedef-ing rvalue references
to "moveType" when C++0x is available, and otherwise using
a proxy "movable" class. Just to make the transition easier.
Example below.
Any thoughts?
--Jonathan
// begin: movetest.cpp
#include <cstddef>
#include <algorithm>
#if (__cplusplus > 199711L)
// Use the C++0x std::move if available
#include <utility>
namespace cpp0x = std;
#else
// Older versions of C++ use proxy class
namespace cpp0x {
template<class T>
class movable : public T {
public:
movable(T& t):T() { T::swap(t); }
};
template<class T>
movable<T> move(T& t) {
// rely on RVO
return movable<T>(t); }
}
#endif
class dummy {
char* ptr;
std::size_t len;
public:
#if (__cplusplus > 199711L) /* c++0x */
typedef dummy&& moveType;
#else
typedef cpp0x::movable<dummy>& moveType;
#endif
dummy(): ptr(0), len(0)
{ }
dummy(std::size_t n)tr(n ? new char[n] : 0), len(n)
{ }
dummy(const dummy& d)tr(d.len ? new char[d.len] : 0), len(d.len)
{ }
dummy(moveType d)tr(d.ptr), len(d.len) {
d.ptr = 0, d.len = 0;
}
dummy& operator=(moveType d) {
d.swap(*this);
return *this;
}
void swap(dummy& d) {
std::swap(ptr, d.ptr);
std::swap(len, d.len);
}
};
int main () {
dummy a(5);
dummy b;
b = cpp0x::move(a);
return 0;
}
// end: movetest.cpp