Is it possible to define a 'move-and-swap idiom' equivalent in C++03

不想你离开。 提交于 2021-01-27 16:10:17

问题


I'm bound to C++03 and I have a non-copyable object (e.g. holding a resource).

I need to use move-and-swap semantics to be able to do something similar and avoid copies:

MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test;
    test = returnMyClass(); // need to avoid copies
}

Is it possible to respect all these requirements in C++03?

It is basically the same case of this, but for C++03.


To put the question in other words:

Given a non-copyable class MyClass, is it somehow possible in C++03 to do MyClass test = returnMyClass();?

I'm afraid the answer is simply no, but maybe I'm missing some trick.


回答1:


There is no magic in move semantics. It's just another overload. The rvalue reference thing is a nice convenience that is not really essential.

template <class T>
struct rref { 
    rref (T& t) : t(t) {}
    T& t; 
};

template<class T>
rref<T> move(const T& t) {
   return rref<T>(const_cast<T&>(t));
}

// you now can do a "move ctor"
class Foo {
   Foo(rref<Foo>) { ... }
};

Now you also need NRVO to kick in for this to work. It is not guaranteed by the standard, but it is provided by pretty much every implementation. To ensure it really happens, you may declare but not define a copy ctor.

Full working demo




回答2:


If you can initialize your object test at declaration you will be able to avoid copying because copy elision will be performed.

class MyClass
{
  public:
    MyClass(){std::cout << "Default Constructor" << std::endl;}
    MyClass(const MyClass &){std::cout << "CPYConstructor" << std::endl;}
    ~MyClass() {std::cout << "Destructor" << std::endl;}

};


MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test = returnMyClass(); // need to avoid copies
}

Output:

Default Constructor
Destructor


来源:https://stackoverflow.com/questions/60296661/is-it-possible-to-define-a-move-and-swap-idiom-equivalent-in-c03

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!