gpt4 book ai didi

c++ - std::string 是一个对象吗?

转载 作者:行者123 更新时间:2023-11-30 01:52:14 24 4
gpt4 key购买 nike

只是着眼于优化一些 std::map 代码。该 map 包含对象,可通过字符串标识符访问。

例子:

std::map<std::string, CVeryImportantObject> theMap;

...

theMap["second"] = new CVeryImportantObject();

现在,当将查找函数用作 theMap->find("second") 时,字符串将转换为 std::string("second") ,这会导致新的字符串分配(当在 Visual Studio 中使用 IDL=2 时)。

1。是否有可能使用仅包含字符串的类来避免此类分配?

我也有意尝试使用另一个 String-Class:

std::map<CString, CVeryImportantObject> theMap;

此代码也有效。但是 CString 确实是一个对象。

并且:如果您从 map 中删除一个对象,我需要同时释放相关对象和 key ,对吗?

有什么建议吗?

最佳答案

Now, when using the find-function as theMap->find("second"), the String is converted into std::string("second"), which causes new string allocations (over all when using IDL=2 with Visual Studio).

这是一个标准问题,已在 C++14 中针对有序容器修复。 VS 的最新版本 VS 14 CTP(预发布)包含 a fix for this issue ,以及其他实现的新版本。

如果你需要避免分配,你可以尝试像llvm::StringRef这样的类可以引用std::string或字符串文字可互换,但随后您将不得不尝试从外部处理所有权。

你可以尝试类似 unique_ptr<char[], maybe_delete> 的东西有时会删除内容。不过,这有点困惑。

And: If you remove an object from the map, I'll need to release both the related object and the key, do I?

map 会自动为您销毁键和值。对于释放自己资源的类,如 std::string ,这是编写 C++ 的唯一明智的方式,然后您可以删除而不用担心资源清理。

关于c++ - std::string 是一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24937346/

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