我在一个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!