How to implement move functionality without any reference to std::move or std::swap?

177 views Asked by At

How to implement move functionality without any reference to std::move or std::swap?

What is a standard function prototype acceptable by STL, and how to use it?

Please, give an example. I tried to search StackOverflow.

I want to implement this for a class in a project which does not have any reference to STL (and it must not!). But, in a test project, I use STL. Anything in StackOverflow references the std::move or std::swap functions. I have to avoid them to satisfy both goals.

2

There are 2 answers

13
Igor Polkovnikov On

Is this sufficient? Should another funciton be implemented?

MyClass(MyClass&& o)
{
    memcpy(this, &o, sizeof(MyClass));    
};

Thank you, john! Amending with:

MyClass& operator=(const MyClass && o) noexcept
{
    memcpy(this, &o, sizeof(MyClass));
    return *this;
}

Is it good enough?

6
Michaël Roy On

std::move() is done by casting to a T&&. You can cast by hand, or create your own move function:

template <typename T>
constexpr T&& move(T& t) noexcept
{
    return static_cast<T&&>(t);
}