Hey guys, I had a few questions regarding the implementation of the (extremely cool) optional template class.
First of all, I see that the data itself is stored in the m_data member of the optional_base class. This is essentially a byte array (char's) that the stores the object's data. This data is then cast to the appropriate type whenever needed via the GetT() function. My question is, why it implemented this way instead of using a template type?
Secondly, I see a lot of stuff like this:
What's up with all those const's? I've never seen them used like that before.
Finally, I created a very simple class that allocates memory in the constructor and releases it in the destructor. When I use this class as the template parameter for my optional object, I end up getting the destructor called too soon. Here's an example to show you what I mean:
Display All
Thanks in advance for any help you can provide
First of all, I see that the data itself is stored in the m_data member of the optional_base class. This is essentially a byte array (char's) that the stores the object's data. This data is then cast to the appropriate type whenever needed via the GetT() function. My question is, why it implemented this way instead of using a template type?
Secondly, I see a lot of stuff like this:
What's up with all those const's? I've never seen them used like that before.
Finally, I created a very simple class that allocates memory in the constructor and releases it in the destructor. When I use this class as the template parameter for my optional object, I end up getting the destructor called too soon. Here's an example to show you what I mean:
Brainfuck Source Code
- #define DATA_SIZE 50
- class tile
- {
- int x, y;
- char *data;
- public:
- tile(void);
- ~tile(void) {if (data) {delete data;}}
- //implementation
- void draw(void); //simply prints the string right now
- //accessors
- //...
- //(pretend there are accessor functions here)
- //...
- }; //end class tile
- //-----------------------------------
- tile::tile(void)
- {
- data = new char[DATA_SIZE];
- memset(data,0,DATA_SIZE);
- x = 0; y = 0;
- } //end tile::tile()
- //-----------------------------------
- optional<tile> do_stuff(void)
- {
- optional<tile> ret;
- tile temp; //temp var; very ugly...
- char str[DATA_SIZE];
- //get a string and store it
- cout << "\nwhat string? ";
- cin >> str;
- temp = str;
- ret = temp;
- //****************************
- //When this function returns, tile::~tile() is called and kills tile::data
- //****************************
- return ret;
- } //end do_stuff()
- //-----------------------------------
- int main(void)
- {
- optional<tile> ret;
- ret = do_stuff();
- if (ret.valid()) {cout << "\n\n"valid\n";}
- else {cout << "\n\ninvalid\n";}
- } //end main()
Thanks in advance for any help you can provide
![:)](https://www.mcshaffry.com/GameCode/wcf/images/smilies/smile.png)