Jan Rüegg
Jan Rüegg

Reputation: 10035

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?

Upvotes: 3

Views: 619

Answers (1)

Jarod42
Jarod42

Reputation: 217135

The simplest is to wrap your code into a function:

std::unique_ptr<Sensor> make_safe_sensor()
{
    Sensor *sensor;
    GetSensor(&sensor);
    return std::unique_ptr<Sensor>(sensor);
}

std::unique_ptr doesn't give access to the reference to its owning pointer.

Upvotes: 7

Related Questions