gpt4 book ai didi

c++ - std::move 是否应该用于 return-statements 以提高效率?

转载 作者:可可西里 更新时间:2023-11-01 16:31:12 25 4
gpt4 key购买 nike

我不知道下面代码中的 std::move 是做了什么好事还是完全错误?Object 类同时定义了 Move 和 Copy 构造函数。

首先:随着 move :

template<typename T> template <typename F> 
const Object<T> Object<T>::operator*(const F& rhs) const
{
return std::move(Object(*this) *= rhs); // We end in move constructor
}

第二种:不 move :

template<typename T> template <typename F> 
const Object<T> Object<T>::operator*(const F& rhs) const
{
return Object(*this) *= rhs; // We end in copy constructor
}

*= 运算符定义为:

template<typename T> template<typename F>  
Object<T>& Object<T>::operator*=(const F& rhs)
{
for(int i = 0; i < dimension ; i++)
{
_inner[i] *= rhs;
}
return *this;
}

这是我用来测试它的代码:

Object<double> test(4);
Object<double> test2(test * 4);
std::cout << test2; // works fine

结果第一种情况下,我们以 move 构造函数结束,而在第二种情况下,我们以复制构造函数结束。

无论哪种情况,代码都会编译。

一个比另一个更有效,因为我认为将新对象移出而不是将其复制出来会更快吗?

附加信息:我使用以下编译器:g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

最佳答案

Is one more efficient than the other since I would assume it is faster to move the new object out instead of copying it out?

是的,在这里使用 std::move 会更有效,假设对象具有比复制更有效的 move 语义。

通常,当返回临时变量或局部变量时,会自动使用 move 语义。但是,在这种情况下,您不是直接返回临时值,而是返回 operator*= 返回的 lvalue 引用。由于 lvalue 不会被 move ,在这种情况下您确实需要 std::move 将其转换为 rvalue

但是,您不应返回 const 值,因为这会阻止返回值被用于 move 初始化(或 move 分配)另一个对象。您的示例将通过复制 返回值来初始化 test2,尽管该拷贝可能会被省略。

或者,您可以使用局部变量实现它:

template<typename T> template <typename F> 
Object<T> Object<T>::operator*(const F& rhs) const
{
Object lhs(*this);
lhs *= rhs;
return lhs;
}

不仅可以 move 返回值,而且可以省略 move 本身。

关于c++ - std::move 是否应该用于 return-statements 以提高效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16605768/

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