mercredi 23 septembre 2015

Fill std::unique_ptr afterwards

I have a function that takes a pointer to a pointer, and fills in the value:

void GetSensor(Sensor **sensor);

Normally, I have to do this to create the sensor and free it:

Sensor *sensor;
GetSensor(&sensor);
// Do something with the sensor
delete sensor;

Now I would like to use an std::unique_ptr for the same task. I know I can do this:

std::unique_ptr<Sensor> *safe_sensor;
Sensor *sensor;
GetSensor(&sensor);
safe_sensor.reset(sensor);
// Do something with the sensor
// safe_sensor will free the sensor pointer

Can I somehow avoid the step with the temporary sensor variable? Would this work?

std::unique_ptr<Sensor> *safe_sensor;
GetSensor(&safe_sensor.get());
// Do something with the sensor
// Will the free work correctly here?

Aucun commentaire:

Enregistrer un commentaire