Why is this optimized by g ++? At least I think that what's going on

When I run the following code

#include <iostream>
int main(int argc, char *argv []) {

  std::string simpleString("this is just a simple string");

  std::cout << "simpleString = " << simpleString << std::endl << std::endl;

  std::string one = (simpleString + ", one");

  const char * oneCharStar = one.c_str();
  std::cout << "simpleString + one: '" << oneCharStar << "'" << std::endl;

  const char * twoCharStar = (simpleString + ", two").c_str();
  std::cout << "simpleString + two: '" << twoCharStar << "'" << std::endl;

  return 0;
}

on my Fedora Core 23 computer, on which uname -a reports:

"Linux glorp 4.5.7-202.fc23.x86_64 # 1 SMP Tue Jun 28 18:22:51 UTC 2016 x86_64 x86_64 x86_64 GNU / Linux"

and g ++ --version says

"g ++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)"

the first output reads "it's just a simple line, one", and the second output shows an empty line.

I suppose there is some kind of optimization here, but on my previous Ubuntu machine (16.mumble, calm down) this code worked as I expected. I just found that when I recompiled my application (using the same make files, etc.) on the new computer, this code failed, as described above.

, , :

$uname -a Linux t4240rdb

3.12.37-rt51 + g43cecda # 2 SMP Fri Mar 4 18:18:03 EST 2016 ppc64 GNU/Linux

$g++ --version

g++ (GCC) 4.9.2

Copyright (C) 2014 Free Software Foundation, Inc.

? !

+4
1
const char * twoCharStar = (simpleString + ", two").c_str();

(simpleString + ", two") .

std::string , c_str() . std::string . , twoCharStar .

- undefined.

+9

Source: https://habr.com/ru/post/1680353/


All Articles