-
class reference function
What does the reference operator do in this case:
Code:
const dataset_buf& read_data_set (const string& dataname) {
How would I use this function? dataset_buf is another class, this function mentioned above is in the class "dataset_loader". It is supposed to return a reference to dataset_buf.
Code:
class dataset_loader {
public:
static void Init () { Exception::dontPrint(); }
dataset_loader (const string& filename) : hdf5_file(filename, H5F_ACC_RDONLY), datasets() {}
~dataset_loader () {hdf5_file.close(); }
const dataset_buf& read_data_set (const string& dataname) {
Code:
class dataset_buf{
dataset_buf& operator= (const dataset_buf& other) { ...
-
It depends on what you want to do with the dataset_buf object that it returns a reference to. If you're going to call a single function on it, you can just chain the functions together: Code:
my_dataset_loader.read_data_set(dataname).output_results();
If you're going to be doing a lot of work with the dataset_buf and want to work on the exact instance that is returned, you'll want to create a reference variable to refer to that same instance: Code:
dataset_buf& returned_dataset = my_dataset_loader.read_data_set(dataname);
returned_dataset.do_some_work();
returned_dataset.do_more_work();
returned_dataset.output_results();
If you want to use a copy of the results, (which may be unlikely since the function returns a reference on purpose) then make a normal, non-reference variable to save the return value. This will make a copy so any changes won't affect the original instance returned by the function: Code:
dataset_buf returned_dataset = my_dataset_loader.read_data_set(dataname);
returned_dataset.do_some_work();
returned_dataset.do_more_work();
returned_dataset.output_results();
The copy might be expensive, so use the reference version unless you really want to avoid changing the original value.