关于 std::move
,根据 http://en.cppreference.com/w/cpp/utility/move,这是我可以解释的内容:-
- 如果我想转移所有权,我必须调用
std::move
(或者在极少数情况下调用std::forward
)。 std::move
的职责是调用operator=(A&& other)
。- move 操作最重要的步骤应该在
operator=(A&&)
中实现。 - 确保
operator=(A&&)
被调用是很棘手的。它需要一个特殊的转换器。 - C++ 世界中只有两个转换器可以将变量转换为
xvalue
(&&):std::move
和std::forward
。
问题
在我的代码中添加了很多std::move(std::unique_ptr)
之后,我开始担心像转让所有权这样的基本功能,我不得不严重依赖标准库(标准::
)。
我真的必须使用 std::move
来转移所有权吗?
在代码库的许多地方进行垃圾邮件和硬编码调用 std::move
是否是获得高标准程序的正确方法?
是否应该封装std::move
?
他们实际上是一个问题,但从不同的角度提出。
编辑
根据要求,这是我的试错。编译正常。
我对代码没有问题,但我担心它的方法/模式。
https://ideone.com/y8Pcgf
class T{
public: int value;
public: T(int a=1234){
value = a;
}
};
int main() {
std::unique_ptr<T> t1 = std::unique_ptr<T>(new T(1));
void* databaseNew=operator new [](sizeof(std::unique_ptr<T>));
std::unique_ptr<T>* t1ptr=static_cast<std::unique_ptr<T>*>(databaseNew);
new (t1ptr) std::unique_ptr<T>(std::move(t1));
return 0;
}
最佳答案
经验法则:
如果您处于推导的 x 值上下文中,请使用 std::forward
:
template<class T>
void foo(T&& t) // T is deduced x-value, so we forward it
{
bar(std::forward<T>(t));
}
否则使用std::move
template<class T>
void foo1(std::vector<T> v) // although vector<T> is deduced, it's not an x-value
{
bar(std::move(v)); // so move it
}
template<class T>
void foo2(std::vector<T>&& v) // although vector<T> is deduced, it's not an x-value.
// In this case an r-value reference
{
bar(std::move(v)); // so move it
}
template<class T>
void foo3(std::vector<T>& v) // although vector<T> is deduced, it's not an x-value.
// In this case an l-value reference
{
bar(std::move(v)); // so move it
}
void foo4(std::vector<int> v) // complete type
{
bar(std::move(v)); // so move it
}
void foo5(std::vector<int> const & v) // const reference
{
bar(v); // not much point in moving it. std::move would cast it
// to std::vector<int> const&&, which although is detectable
// decays to std::vector<int> const&
}
which although is detectable... what?
如果不一定建议编写这样的代码,这是允许的:
#include <iostream>
struct X
{
void foo() const &
{
// do one thing...
std::cout << "one thing\n";
}
void foo() const &&
{
// do something else...
std::cout << "or another\n";
}
};
int main()
{
const X x;
x.foo();
std::move(x).foo();
}
const 右值引用确实存在,只是没有人使用它们,因为没有合理的用例。
关于c++ - 垃圾邮件 std::move 是要走的路吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39566141/