gpt4 book ai didi

c++ - 显式选择复制分配

转载 作者:IT老高 更新时间:2023-10-28 12:43:41 25 4
gpt4 key购买 nike

在 C++11 中,如果复制和移动赋值都可用,编译器会在参数是左值时自动选择复制赋值,如果是右值则自动选择移动赋值。使用 std::move 可以显式选择左值的移动分配。但是怎么可能显式地选择右值的复制赋值呢?

代码示例:

#include <iostream>

class testClass
{
public:
testClass &operator=(const int &other) {
std::cout << "Copy assignment chosen." << std::endl;
return *this;
}

testClass &operator=(int &&other) {
std::cout << "Move assignment chosen." << std::endl;
return *this;
}
};

int main(int argc, char *argv[])
{
int a = 4;
testClass test;

test = a; // Selects copy assignment
test = 3; // Selects move assignment

test = std::move(a); // Selects move assignment
// test = std::copy(3); // <--- This does not work

return 0;
}

最佳答案

一种可能的方法是编写自己的 copy 将对象绑定(bind)到左值引用:

template <class T>
constexpr T& copy(T&& t) noexcept
{
return t;
}

你可以这样测试:

test = copy(a);
test = copy(3);
test = copy(std::move(a));

你可以把这个函数放在你自己的命名空间中以保持干净。你也可以为它选择一个更好的名字。


为了解决对终身问题的恐惧,这里有一些注意事项:

  • 这个copy 函数接受一个引用并立即返回相同的引用。这意味着调用者负责控制生命周期。
  • 临时对象的生命周期一直持续到语句结束。这使得对象保持足够长的时间以传递到 = 的左侧。

关于c++ - 显式选择复制分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017101/

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