《UE4游戏开发》之 《MoveTemp函数的理解》

  1. 源码
/**
 * MoveTemp will cast a reference to an rvalue reference.
 * This is UE's equivalent of std::move except that it will not compile when passed an rvalue or
 * const object, because we would prefer to be informed when MoveTemp will have no effect.
 */
template <typename T>
FORCEINLINE typename TRemoveReference<T>::Type&& MoveTemp(T&& Obj)
{
    
    
	typedef typename TRemoveReference<T>::Type CastType;

	// Validate that we're not being passed an rvalue or a const object - the former is redundant, the latter is almost certainly a mistake
	static_assert(TIsLValueReferenceType<T>::Value, "MoveTemp called on an rvalue");
	static_assert(!TAreTypesEqual<CastType&, const CastType&>::Value, "MoveTemp called on a const object");

	return (CastType&&)Obj;
}
  1. 从注释看:该函数的作用是将一个引用转化成右值引用,与标准库std::move功能一致,不同的是当传递的参数是一个右值或者传递的参数是cosnt object时,将会断言提示,且MoveTemp作用不会起作用
  2. 右值引用参考:https://blog.csdn.net/qq_30683329/article/details/88532673
/** 当Move Constructor存在时,调用的时Move Constructor;否则调用的
		时复制构造函数【复制构造函数和构造函数消耗都比较大】,可以通过移动
		构造函数节约性能
	[7/22/2020 ZC] */
  1. 尽量给类添加移动构造和移动赋值函数,而减少拷贝构造和拷贝赋值的消耗。 移动构造,移动赋值要加上noexcept,用于通知标准库不抛出异常。且函数传参也多用右值,返回值也可以用右值

猜你喜欢

转载自blog.csdn.net/qq_21919621/article/details/107507706