roulette01
roulette01

Reputation: 2462

Pointing to an object that's going out of scope

I want to allocate an object of type custom_type_t (operator= is not available for this custom_type_t and I'm unable to modify that part of the codebase) depending on whether a condition is met and, if it's not met, that object should not be created at all.

I was initially thinking I could do:

// create the object even if it's not needed
custom_type_t object; // just use their default constructor which hopefully isn't expensive

if (condition_met) {
  object = custom_type_t(constructor arguments);
} 

However, this isn't possible because there's no operator=.

I'm wondering if there's a way in which I can do something like the following:

int* custom_type_t ptr;
if (condition_met) {
  custom_type_t object = custom_type_t(constructor arguments);
  ptr = &custom_type_t;
} // but object may go out of scope here, so ptr may end up pointing to garbage

// ptr will be used later on if condition_met == true

But I need to have object actually remain valid so ptr doesn't point to garbage?

Upvotes: 1

Views: 58

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51815

Your problems/confusion seem to lie in separating the idea of creating an object from that of explicitly declaring that object. You can quite easily (conditionally) create your object, and subsequently use it, by just declaring a pointer to it.

Using a simple 'raw' pointer, something like this (for the sake of the example, I have assumed that two int values are required for the constructor arguments):

void function()
{
    custom_type_t* pObject = nullptr;
    if (condition_met) {
        pObject = new custom_type_t(42, -9);
    }
    // ...

    delete pObject; // If still nullptr, no problem - does nothing.
}

Or, better, using a smart pointer:

void function()
{
    std::unique_ptr<custom_type_t> pObject;
    if (condition_met) {
        pObject = std::make_unique<custom_type_t>(42, -9);
    }
    //...

    // "pObject" is automagically freed when this function returns.
}

In either of the above cases, you can use *pObject in expressions where you would otherwise use object, and you can use pObject->memberFunc() instead of object.memberFunc().

Upvotes: 3

Related Questions