将结构中的引用用于其他结构是否安全

时间:2016-07-29 13:38:55

标签: c++

我在一个DataStorage结构中有2个结构。我最终想要的是有可能独立使用第一个结构,并且能够保存DataStorage并确保前两个将被保存。这可能不相关,因为问题是 - 这段代码安全吗?

请看一下代码,它会更好地说明一切。 我相信我的方法没问题,但是由于内存泄漏和其他意外行为,我一直担心使用指针和引用。

#include < iostream > 
#include < string >
  //---------------------------
  //two structures to hold some data
  //and a structure to hold 2 structures
  struct settings_t {
    uint8_t myBaseID = 68;
    uint8_t reserved1;
  } settingsD;

struct values_t {
  unsigned long longValue0;
};

//struct in question, will also later be passed to template class like
//some_template_type <DataStorage>save; 
struct DataStorage {
  settings_t & settings = settingsD;
  values_t valueStore;
};
//--------------------------
//function that generates new structure
settings_t generateNew() {
    settings_t ret;
    ret.myBaseID = 66;
    return ret;
  }
  //new test instance of datastorage
void test1() {
  DataStorage ds1;
  std::cout << "Hello, " << ds1.settings.myBaseID << "!\n";
}

int main() {
  DataStorage ds;
  ds.settings.myBaseID = 65;

  std::cout << "Hello, " << ds.settings.myBaseID << "!\n";
  std::cout << "Hello, " << settingsD.myBaseID << "!\n";
  test1();

  ds.settings = generateNew();

  std::cout << "Hello, " << ds.settings.myBaseID << "!\n";
  std::cout << "Hello, " << settingsD.myBaseID << "!\n";
  test1();
}

结果是(根据需要):

Hello, A!
Hello, A!
Hello, A!
Hello, B!
Hello, B!
Hello, B!

0 个答案:

没有答案