C++字符串文字与 const 字符串
我知道 C/C++ 中的字符串文字具有静态存储持续时间,这意味着它们“永远”存在,即只要程序运行。
因此,如果我有一个被频繁调用的函数,并且使用像这样的字符串文字:
void foo(int val)
{
std::stringstream s;
s << val;
lbl->set_label("Value: " + s.str());
}
其中 set_label 函数采用 const std::string& 作为参数。
我应该在这里使用 const std::string 而不是字符串文字,还是没有区别?
我需要尽可能减少运行时内存消耗。
编辑:
我的意思是将字符串文字与在某种常量头文件中初始化的 const std::string prefix("Value: "); 进行比较。
另外,这里的串联返回一个临时值(让我们称之为 Value: 42
,并且对此临时值的 const 引用被传递给函数 set_text()
,我是否正确在此
再次感谢您!
I know that string literals in C/C++ have static storage duration, meaning that they live "forever", i.e. as long as the program runs.
Thus, if I have a function that is being called very frequently and uses a string literal like so:
void foo(int val)
{
std::stringstream s;
s << val;
lbl->set_label("Value: " + s.str());
}
where the set_label function takes a const std::string&
as a parameter.
Should I be using a const std::string
here instead of the string literal or would it make no difference?
I need to minimise as much runtime memory consumption as possible.
edit:
I meant to compare the string literal with a const std::string prefix("Value: ");
that is initialized in some sort of a constants header file.
Also, the concatenation here returns a temporary (let us call it Value: 42
and a const reference to this temporary is being passed to the function set_text()
, am I correct in this?
Thank you again!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的程序每次都运行相同的文字。没有比这更有效的存储形式了。将构造 std::string 并在堆上复制,然后在每次函数运行时释放它,这完全是浪费。
Your program operates on the same literal every time. There is no more efficient form of storage. A std::string would be constructed, duplicated on the heap, then freed every time the function runs, which would be a total waste.
这将使用更少的内存并运行得更快(如果您的编译器支持,请使用
snprintf
):要获得更快的实现,请查看 C++ 性能挑战:整数到 std::string 转换
This will use less memory and run much faster (use
snprintf
if your compiler supports it):For even faster implementations, check out C++ performance challenge: integer to std::string conversion
您将如何构建 const std::string ?如果您从某个字符串文字执行此操作,最终会变得更糟(或者如果编译器做得很好的话则相同)。字符串文字不会消耗太多内存,而且静态内存也不会消耗太多,这可能不是您所需要的内存。
如果您可以从文件中读取所有字符串文字,并在不再使用字符串时将内存返还给操作系统,则可能有某种方法可以减少内存占用(但它可能会大大减慢程序速度)。
但在做这种事情之前,可能还有很多其他方法可以减少内存消耗。
How will you build your const std::string ? If you do it from some string literral, in the end it will just be worse (or identical if compiler does a good job). A string literal does not consumes much memory, and also static memory, that may not be the kind of memory you are low of.
If you can read all your string literals from, say a file, and give the memory back to OS when the strings are not used any more, there may be some way to reduce memory footprint (but it will probably slow the program much).
But there is probably many other ways to reduce memory consumption before doing that kind of thing.
将它们存储在某种资源中,并根据需要加载/卸载它们。
Store them in some kind of resource and load/unload them as necessary.