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

标签 c++ string stdmap

只是着眼于优化一些 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/

相关文章:

java - Go 中 String 的 MD5 摘要与 Java 不同

c++ - std::map 中的 find() 函数返回一个值,尽管没有有效的键

c++ - std::map clear() 崩溃 - 多线程

c++ - 推进标准 map 的迭代器

c++ - 为什么不能使用 constexpr if (表达式) ,即使表达式可以在编译时求值

r - 跨两个数据框与具有多个条目进行匹配的某些观察结果进行匹配

c++ - 制作一个简单的 C++ 键盘记录器

arrays - 为什么在 PowerShell 中使用逗号连接字符串?

c++ - 如何在打开 gdb 时添加额外的延迟

c++ - 在 lambda 表达式中指定捕获的变量的目的是什么?