gpt4 book ai didi

c++ - 是否可以在 C++03 中定义 'move-and-swap idiom' 等效项

转载 作者:行者123 更新时间:2023-12-02 15:56:50 24 4
gpt4 key购买 nike

我绑定(bind)到C++03并且我有一个不可复制的对象(例如持有资源)。

我需要使用 move 和交换语义才能执行类似的操作并避免复制:

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 中满足所有这些要求?

this 的情况基本相同,但对于 C++03。

<小时/>

换句话说:

给定一个不可复制MyClass,在C++03中是否有可能执行MyClass test = returnMyClass ();?

恐怕答案是,但也许我错过了一些技巧。

最佳答案

move 语义并没有什么魔力。这只是另一种重载。右值引用确实很方便,但并不是必需的。

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 来启动才能使其发挥作用。标准不保证它,但几乎每个实现都提供它。为了确保它确实发生,您可以声明但不定义复制因子。

Full working demo

关于c++ - 是否可以在 C++03 中定义 'move-and-swap idiom' 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60296661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com