在静态存储器情况下串计数 [英] Strings in static memory instances count

查看:101
本文介绍了在静态存储器情况下串计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知编译时类似C的字符串保存在静态存储器,因为只有一个实例。比如我有两个真正在GCC 4.6运行下面的例子。但我不知道是不是总是正确的,可以是便携式的。在两个C和C ++的行为是有趣的。

 的#include<&iostream的GT;布尔amIportable(为const char *值){
  为const char * slocal =你好;
  回报(slocal ==值);
}诠释主(){
  为const char * s =你好;
  性病::法院LT&;<的std :: boolalpha
            << amIportable(S)所述;&下;的'\\ n'
            << amIportable(你好)<<的'\\ n';
}


解决方案

没有,这并不总是正确的,也不是可移植的。

合并相同的字符串是由编译器和连接器一起工作进行了优化。 GCC和微软的编译器的最新版本都支持它,但只有当一定的优化开关设置。

和它不只是开或关功能。不同的编译器和不同的优化设置也将影响的此积极执行的。例如,有时字符串仅一个独立的功能的范围内汇集,其他时候,它发生在翻译单元的水平,并且仍然其他时间则链接器可能参与到多个翻译单元做到这一点。

这是允许的,因为C和C ++标准,离开这个行为依赖于实现的。

As I know compiletime C-like strings are kept in static memory as only one instance. For instance I got both true on gcc 4.6 running example below. But I wonder is it always true and can be portable. Behavior on both C and C++ is interesting.

#include <iostream>

bool amIportable(const char* value) {
  const char* slocal = "Hello";
  return (slocal==value);
}

int main() {
  const char* s = "Hello";
  std::cout << std::boolalpha 
            << amIportable(s) << '\n'
            << amIportable("Hello") << '\n';
}

解决方案

No, this is not always true, nor is it portable.

Merging identical string literals is an optimization that is performed by the compiler and the linker working together. Recent versions of both GCC and Microsoft's compiler both support it, but only when certain optimization switches are set.

And it's not just an "on" or "off" feature. Different compilers and different optimization settings will also affect how aggressively this is performed. For example, sometimes string literals are pooled only within the scope of an individual function, other times it happens at the level of the translation unit, and still other times the linker might get involved to do it across multiple translation units.

This is allowed because the C and C++ standards leave this behavior as implementation-dependent.

这篇关于在静态存储器情况下串计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆