C / C ++:指针优化字符串常量 [英] C/C++: Optimization of pointers to string constants

查看:169
本文介绍了C / C ++:指针优化字符串常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看一看这个code:

#include <iostream>
using namespace std;

int main()
{
    const char* str0 = "Watchmen";
    const char* str1 = "Watchmen";
    char* str2 = "Watchmen";
    char* str3 = "Watchmen";

    cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl;
    cerr << static_cast<void*>( const_cast<char*>( str1 ) ) << endl;
    cerr << static_cast<void*>( str2 ) << endl;
    cerr << static_cast<void*>( str3 ) << endl;

    return 0;
}

其中产生一个输出这样的

Which produces an output like this:

0x443000
0x443000
0x443000
0x443000

这是对的 G ++ 的编译器下的 Cygwin的的运行。该指针都指向同一个位置,即使没有优化开启( -O0 )。

This was on the g++ compiler running under Cygwin. The pointers all point to the same location even with no optimization turned on (-O0).

该编译器优化总是这么多,它会搜索所有的字符串常量,看看他们是平等的吗?可这种行为被倚重?

Does the compiler always optimize so much that it searches all the string constants to see if they are equal? Can this behaviour be relied on?

推荐答案

这是一个非常简单的优化,大概以至于大多数编译器作者甚至不认为这是一个优化的多的。设置优化标志来的最低水平并不意味着是完全天真毕竟。

It's an extremely easy optimization, probably so much so that most compiler writers don't even consider it much of an optimization at all. Setting the optimization flag to the lowest level doesn't mean "Be completely naive," after all.

编译器将在他们在合并重复字符串是如何积极的变化。他们可能会限制自己一个子程序 - 把那四个声明不同的功能,而不是一个单一的功能,你可能会看到不同的结果。其他人可能会做一个完整的编译单元。其他人可能会依赖于连接器来编译多个单位之间进一步融合。

Compilers will vary in how aggressive they are at merging duplicate string literals. They might limit themselves to a single subroutine — put those four declarations in different functions instead of a single function, and you might see different results. Others might do an entire compilation unit. Others might rely on the linker to do further merging among multiple compilation units.

您不能依靠此行为,除非您的特定编译器的文件说,你可以。语言本身就是没有这方面的要求。我会警惕依靠它在我自己的code,即使便携性是不是一个问题,因为行为承担责任,甚至不同版本的单一供应商的编译器之间切换。

You can't rely on this behavior, unless your particular compiler's documentation says you can. The language itself makes no demands in this regard. I'd be wary about relying on it in my own code, even if portability weren't a concern, because behavior is liable to change even between different versions of a single vendor's compiler.

这篇关于C / C ++:指针优化字符串常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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