gpt4 book ai didi

c++ - 为什么我的交换方法会干扰 make_move_iterator?

转载 作者:行者123 更新时间:2023-11-30 01:23:47 25 4
gpt4 key购买 nike

这个让我彻底糊涂了。在下面的示例中,我得到了错误:

error C2664: 'void std::unique_ptr<_Ty>::swap(std::unique_ptr<_Ty> &&)' : cannot convert parameter 1 from 'const std::unique_ptr<_Ty>' to 'std::unique_ptr<_Ty> &&'

我完全不知道它是如何在我的交换函数中结束的,也不知道它为什么会成为问题。 有趣的是,如果我更改 void swap(const one& other) 的签名并将常量删除为 void swap(one& other) 一切正常。 如果我更改了 void swap(const one& other) 的签名并将常量删除为 void swap(one& other) 它在 VS2010 中编译但在 GCC 中仍然损坏。如果没有交换过载,则没有问题。

//-----------------------------------------------------------------------------
class one
{
public:
one(){}
one(one&& other) : x(std::move(other.x)) {}
one& operator=(one&& other){ x = std::move(other.x); return *this; }

void swap(const one& other){ x.swap(other.x); }
void swap(one&& other){ x.swap(std::move(other.x)); }

private:
one(const one&);
one& operator=(const one&);

std::unique_ptr<int> x;
};

//-----------------------------------------------------------------------------
void swap(one& left, one& right)
{
left.swap(right);
}

//-----------------------------------------------------------------------------
void swap(one&& left, one& right)
{
right.swap(std::move(left));
}

//-----------------------------------------------------------------------------
void swap(one& left, one&& right)
{
left.swap(std::move(right));
}

//-----------------------------------------------------------------------------
class two
{
public:
two(){}
two(two&&){}
two& operator=(two&&){ return *this; }

operator one(){return one();}

private:
two(const two&);
two& operator=(const two&);
};

//-----------------------------------------------------------------------------
int main()
{
std::vector<two> twos(10);
std::vector<one> ones(std::make_move_iterator(twos.begin()), std::make_move_iterator(twos.end()));
}

编辑:非恒定性要求是有道理的。完全是我的疏忽。为什么它首先调用交换?

(供引用,我使用的是 VS2010)

Demo of it broken

Demo of it still broken, but this 'fix' works in VS2010

最佳答案

// other can't be const since swap modifies it
void swap(one& other){ x.swap(other.x); }

// Why swapping? (swap on rvalues don't work either since it's pointless.)
//Just move the other
void swap(one&& other){ x = std::move(other.x); }

关于c++ - 为什么我的交换方法会干扰 make_move_iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14486236/

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