1

This is a piece of code from Gem5 simulator, I am trying to understand the doInit() method (line 17), is it initializing the storage variable (allocated as char array) with Storage object

  1 
  2 
  3 class Storage{
  4     private:
  5             double data;
  6     public:
  7             Storage():
  8                 data(100)
  9             {}
 10             double get_data(){ return data;}
 11             void set_data(double val){ data = val;}
 12 };
 13 class Scalar: public Storage{
 14     private:
 15             char storage[sizeof(Storage)];
 16     public:
 17             void doInit(){
 18                 new (storage) Storage();
 19             }
 20             Storage * data(){
 21                 return reinterpret_cast<Storage *>(storage);
 22             }
 23 };
 24 int main(){
 25     Scalar s;
 26     s.doInit();
 27     
 28     
 29     return 0;
 30 }
~      
Arun Kp
  • 392
  • 2
  • 13
  • 1
    [`#include `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) is wrong in 1st place, and totally distracts me from that question. Wherever you got that from, forget about it, quickly! – πάντα ῥεῖ Sep 24 '22 at 12:48
  • 1
    Same for [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Thomas Weller Sep 24 '22 at 12:49
  • 2
    See [What uses are there for "placement new"?](https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new) and [C++ placement new](https://stackoverflow.com/questions/13370935/c-placement-new). – Jason Sep 24 '22 at 12:50
  • @JasonLiam : Thanks for linking to relevant posts, I tried searching for "new" operator usage, but those posts did not resolve my doubts. Thanks once again – Arun Kp Sep 24 '22 at 12:57

0 Answers0