c++ - 为什么在 std::move 中使用 std::remove_reference ?

标签 c++ syntax reference move-semantics

我尝试实现 std::move , 使用 std::remove_reference ,但是没有它似乎也能工作。请给我一个我的实现失败的例子,其中std::remove_reference是必要的。

template <class type> type && move(type & source) { return (type &&) source; }
template <class type> type && move(type && source) { return (type &&) source; }
std::remove_reference仅用于避免过载 std::move ?
这是一个可以帮助您的测试类:
class test {
public :
    test() { }
    test(const test & source) { std::cout << "copy.\n"; }
    test(test && source) { std::cout << "move.\n"; }
};
不是 How does std::move() transfer values into RValues? 的拷贝因为我的问题包括一个似乎表明 std::remove_reference 的例子在这种情况下没用+子问题。

最佳答案

I tried implementing std::move, which uses std::remove_reference, however it seems to work without it.


是的,它正在工作,因为您明确提供了左值引用的重载。虽然 std::remove_reference仅当您使用转发引用时才相关。
如果你取出这条线:
Godbolt
template <class type> type && move(type & source) { return (type &&) source; }
并将您的功能称为:
test t2 = move(t1); //prints copy
要完成这项工作,您必须使用 std::remove_reference . Try on Godbolt :
template <class type>
std::remove_reference_t<type> && move(type && source)
{
    return
    static_cast<std::remove_reference_t<type>&& >(source);
}

关于c++ - 为什么在 std::move 中使用 std::remove_reference ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63743687/

相关文章:

c++ - std::map::at 在调用堆栈的某处返回警告 "returning reference to temporary"

C++ 独立引用 - 有什么用?

c++ - 重载默认构造函数导致错误

c++ - 在库中隐藏类的使用

c++ - 十六进制转储实用程序 C++ 显示十六进制和 Ascii

循环结构声明C

perl - 我必须怎么做才能防止 Perl 提示 "using a hash as a reference is deprecated"?

groovy - Groovy 中 ==~ 和 != 有什么区别?

MySQL在子查询中引用外部选择

python - 在 python 中,函数返回的是浅拷贝还是深拷贝?