jeudi 21 octobre 2021

Using destructor to finish a task

I am currently experimenting with the following approach to finalize processing some data (pseudo-code).

void run_processing(container datas)
{
    // runs some conversion on data and sends it somewhere.
}

struct process_item
{
    container datas;

    process_item(const char* data)
    {
        datas.add(data);
    }

    ~process_item()
    {
        run_processing(datas);
    }

    operator <<(const char* data)
    {
        datas.add(data);
    }
}

process_item create_item(const char* data)
{
   process_item item(data);
   // Possible additional calls to setup item.
   return item;
}

In my tests this allows for a call.

create_item("my_data") << "additional data" << "even more data";
// Once this piece executes the destructor for process_item is assumed to be called.

The pseudo code doesn't really show the intended benefits but that is besides my question.

I am trying this because I have some restrictions; The processing can't start until all data has been input, and it is not known when that's the case other than when the scope of process_item has ended. For simplicities sake, assume I can't call an additional method or add a flag after the last data is added.

Can the destructor be assumed to be called at the expected time, or is this too risky having the option to differ depending on optimization level and compiler?

Clarification "At the right time" meaning before the next line, the one after the call to create_item executed.

Aucun commentaire:

Enregistrer un commentaire