gpt4 book ai didi

c++ - GCC 中的 unordered_map::insert KeyEqual 异常期间内存泄漏 - 破坏了强大的异常安全保证?

转载 作者:行者123 更新时间:2023-12-03 02:34:58 33 4
gpt4 key购买 nike

我使用的是 GCC 7.3.1,但也在 coliru 上进行了测试,我相信它是版本 9.2.0。使用以下内容构建:

g++ -fsanitize=address -fno-omit-frame-pointer rai.cpp

这是rai.cpp:

#include <iostream>
#include <unordered_map>

int main()
{
try
{
struct MyComp {
bool operator()(const std::string&, const std::string&) const {
throw std::runtime_error("Nonono");
}
};

std::unordered_map<std::string, std::string, std::hash<std::string>, MyComp> mymap;
mymap.insert(std::make_pair("Hello", "There"));
mymap.insert(std::make_pair("Hello", "There")); // Hash match forces compare
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << "\n";
}
}

运行它的结果是:

> ./a.out
Caught exception: Nonono

=================================================================
==72432==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 32 byte(s) in 1 object(s) allocated from:
...

Direct leak of 4 byte(s) in 1 object(s) allocated from:
...

Indirect leak of 60 byte(s) in 2 object(s) allocated from:
...

SUMMARY: AddressSanitizer: 96 byte(s) leaked in 4 allocation(s).

我没有发现 Visual C++(适用于 x64 的 Microsoft (R) C/C++ 优化编译器版本 19.24.28314)存在任何内存泄漏。

这是否破坏了 unordered_map::insert ( https://stackoverflow.com/a/11699271/1958315 ) 的强大异常安全保证?这是 GCC STL 中的错误吗?

最佳答案

标准规定的保证(引用自最新草案):

[container.requirements.general]

Unless otherwise specified (see [associative.reqmts.except], [unord.req.except], [deque.modifiers], and [vector.modifiers]) all container types defined in this Clause meet the following additional requirements:

  • if an exception is thrown by an insert() or emplace() function while inserting a single element, that function has no effects.

[associative.reqmts.except]

For associative containers, if an exception is thrown by any operation from within an insert or emplace function inserting a single element, the insertion has no effect.

[unord.req.except]

For unordered associative containers, if an exception is thrown by any operation other than the container's hash function from within aninsert or emplace function inserting a single element, the insertionhas no effect.

据我了解,“没有效果”意味着“没有内存泄漏”。根据这样的解释,我认为泄漏是一个错误。

关于c++ - GCC 中的 unordered_map::insert KeyEqual 异常期间内存泄漏 - 破坏了强大的异常安全保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59306779/

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