什么是gcc编译器优化?

时间:2020-04-11 09:44:58

标签: c++ gcc compiler-optimization

我可以想到3种情况,编译器可以表示为CSP,然后进行优化,但是我不知道是否这样做。我不假定特定的编译器优化标志,但是,为了确保优化,可以假定已指定-O2或-O3标志。

1)如果在函数调用后未使用参数,则传递参数而不是复制参数

void aFunction(std::string aStr);
...
std::string aString = makeAString(anIntegerInput);
size_t mqSize = aString.size();
aFunction(aString); // or a class method like aClass->aFunction(aString);
std::cout << "Size : " << mqSize << std::endl

因为aFunction调用后未使用aString。从逻辑上可以推断出,编译器是否复制字符串(而不是复制aString)(aFunction的签名不是string &&-在这里不是移动操作)? 使aFunction的输入参数std :: string && aStr强制吗?

2)在这里,创建带有默认构造函数的T对象,然后复制用于初始化Map值的构造函数。

template<typename T>
void aMethod(std::map<std::string, T>& p, const std::vector<std::string>& aVec) {
    p.clear();
    T t;
    for (auto it = aVec.begin(); it != aVec.end(); ++it) {
        p[*it] = t;
    }
}

编译器可以检测到“ t”对象只是默认的构造对象,而不是复制,可以使用默认构造函数初始化p映射的值。

3)我们有一系列的“ theSameString”

std::map<std::string, int> temp{{"john", 5}, {"anna", 7}};
int aValue = temp.find("john");
int anotherValue = temp.find("john");
int yetAnotherValue = temp.find("john");

在这里,编译器是否创建4个不同的“ john” const char *数据结构,或者对于要创建的每个const char *,检查以前的const char *数据结构? 谢谢

1 个答案:

答案 0 :(得分:0)

不允许编译器通过move-constructor调用更改copy-constructor调用,因为它必须遵循语言规则(请注意,如果方法通常具有预期的语义,则它们只是可能与预期的语义不等效的常规方法(我看到一个矩阵类,其中operator++()operator++(int)的行为确实不同,一个增加行,另一列,因此it++;不能用++it;进行优化)))。 / p>

在特定情况下,唯一允许的行为更改是copy/move (constructor) elision。自C ++ 14 new expression起。

它可以做的是as-if rule之后的优化。因此任何不影响可观察行为(I / O,易失性访问)的更改。 “定时”不是一个可观察到的行为,我的意思是,如果您打印代码的经过时间,它就不会禁止对该代码进行优化。

3。)我们有一系列的“ theSameString”

允许编译器,但不是必须这样做。

  • "hello world" == "hello world"可能返回truefalse
  • "hello world" + 6 == "world"可能返回truefalse

(请记住,我们在这里比较指针,而不是内容)。