Quantcast
Channel: Intel® C++ Compiler
Viewing all articles
Browse latest Browse all 1616

C++11 class member initialization for strings

$
0
0

Hello,

I am having an issue, I really can't find an answer to. With the following code, I get a segmentation fault. But only for -O2 / -O3. -O0 and -O1 are fine.

The fault does occur with the C++11 initialization of the string member additionalMessage = ""; If this is not pre-set, it works just fine.

When I replace the member with char*, the code works as expected.

Since the same error occurs with GCC, I guess it is working as intended - but as stated before, I don't come up with the explenation... I could just set  additionalMessage to "" in the constructor, but I just want to know what is happening.

For any clues, I am thankful!

Greetings from Germany,

Hendrik

---------

#include <cstdlib>
#include <iostream>
#include <string>
#include <exception>

using namespace std;


class genericException : public std::exception{
public:

  genericException(){
  }

  virtual char const* what(int lang) const throw () = 0;


protected:
  int additionalId = 0;
  std::string additionalMessage = ""; // does not work
} ;

class ecTest01 : public genericException{
public:
  const char* message[2] = {"Message EN 111", "Message DE 111"};

  ecTest01() : genericException(){
  }

  char const* what() const throw(){
      return message[0];
  }

  char const* what(int lang) const throw(){
      return message[lang];
  }
};

int main(int argc, char** argv){

  try{
    throw ecTest01();
  }catch(genericException& e){

    std::cout << e.what(0) << std::endl;
  }

  return 0;
}

 


Viewing all articles
Browse latest Browse all 1616

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>