Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

*xpos = mystl::move(value_copy);建议修改 #167

Open
shuiyihang opened this issue Nov 7, 2024 · 1 comment
Open

*xpos = mystl::move(value_copy);建议修改 #167

shuiyihang opened this issue Nov 7, 2024 · 1 comment

Comments

@shuiyihang
Copy link

vector插入函数:vector::insert(const_iterator pos, const value_type& value)
else if (end_ != cap_)域中使用了*xpos = mystl::move(value_copy);

我觉得这里不太妥当,首先代码结果没有问题,但是会给阅读者造成不必要困惑。

举个例子有一个自定义类型,实现了移动赋值运算
`auto operator=(test_1&& other) noexcept ->test_1&
{
std::cout << "move\n";
b = other.b;
c = other.c;
other.b = ' ';
other.c = ' ';

    return *this;
}`

我们来分析下:

auto value_copy = value;
xpos = mystl::move(value_copy);
这个过程中先调用了拷贝构造,又使用了移动赋值运算。注释是担心value被改变,所以临时生成一个copy,是的他很有作用。
但为什么不直接
xpos = mystl::move(value);呢,因为这个insert插入的值是const的,所以最终调用的还是copy构造等价于
*xpos = value;

我认为现在的代码中具有迷惑性,不如去掉move,直接*xpos = value;

@Peas-Li
Copy link

Peas-Li commented Nov 11, 2024

因为value可能会被改变,这里的value可能是引用的该vector对象中pos位置后的值,copy_backward后,value的值也就变了,所以必须提前拷贝

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants