gpt4 book ai didi

c++ - 编译但失败的 C++ std::vector> 示例

转载 作者:行者123 更新时间:2023-12-01 23:30:56 27 4
gpt4 key购买 nike

什么是一个简单的 C++ 程序,其中一个 std::vector<std::auto_ptr<T>>编译但无法正确执行,而与 std::vector<std::unique_ptr<T>> 相同的程序编译和工作正常,对于某些数据类型 T

我知道std::auto_ptr已被弃用或删除;我只想要一个涉及容器的示例来激发为什么它被弃用或删除。

我正在使用 g++-10 -std=c++20在 MacOS Big Sur 版本 11.2.1 上。

最佳答案

std::auto_ptr根本不能在标准容器中使用。在这种情况下,它不会保持适当的语义。这是移动语义和 std::unique_ptr 的原因之一。最初是在 C++11 中发明的。 std::auto_ptr在 C++11 中被弃用,并在 C++17 中完全删除。所以在现代编码中根本不要使用它。

官方原因std::auto_ptr此处详细说明了已弃用:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1856.html#20.4.5%20-%20Class%20template%20auto_ptr

给出的例子使用std::sort()std::vector<std::auto_ptr<int>> 上:

With such a design, one could put auto_ptr into a container:

vector<auto_ptr<int> > vec;

However field experience with this design revealed subtle problems. Namely:

sort(vec.begin(), vec.end(), indirect_less());

Depending upon the implementation of sort, the above line of reasonable looking code may or may not execute as expected, and may even crash! The problem is that some implementations of sort will pick an element out of the sequence, and store a local copy of it.

...
value_type pivot_element = *mid_point;
...

The algorithm assumed that after this construction that pivot_element and *mid_point were equivalent. However when value_type turned out to be an auto_ptr, this assumption failed, and subsequently so did the algorithm.

The fix to this problem was to make auto_ptr inhospitable to containers by disallowing "copying" from a const auto_ptr. With such an auto_ptr, one gets a compile time error if you try to put it in a container.

最后的结论是:

Calling any generic code, whether std or not, that will operate on auto_ptr is risky because the generic code may assume that something that looks like a copy operation, actually is a copy operation.

Conclusion:

One should not move from lvalues using copy syntax. Other syntax for moving should be used instead. Otherwise generic code is likely to initiate a move when a copy was intended.

auto_ptr moves from lvalues using copy syntax and is thus fundamentally unsafe.

关于c++ - 编译但失败的 C++ std::vector<std::auto_ptr<T>> 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66267661/

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