是否可以在 C++03 中定义等效的“移动和交换习语" [英] Is it possible to define a 'move-and-swap idiom' equivalent in C++03

查看:48
本文介绍了是否可以在 C++03 中定义等效的“移动和交换习语"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用 C++03 并且我有一个不可复制的对象(例如,持有一个资源).

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

我需要使用 move-and-swap 语义来做类似的事情并避免复制:

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
}

是否可以在 C++03 中遵守所有这些要求?

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

this,但适用于 C++03.

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

换句话说:

给定一个不可复制MyClass,是否可以在C++03中以某种方式执行MyClass test = returnMyClass();?

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.

推荐答案

移动语义没有魔法.这只是另一个过载.右值引用是一种很好的便利,但并不是必需的.

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>) { ... }
};

现在您还需要 NRVO 来启动此功能.标准不保证它,但几乎每个实现都提供了它.为确保它真的发生,您可以声明但不定义复制构造函数.

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.

完整的工作演示

这篇关于是否可以在 C++03 中定义等效的“移动和交换习语"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆