Search code examples
c++memory-managementpass-by-referencestdvectortemporary-objects

C++: return a std::vector<> member, by reference, to a temporary object


I have two functions.

function1 calls function2, which returns a reference to an object, that I then use to call a public function.

function1(function2).returned_object.mymethod();

This is a fairly unwieldy way to do things, but it works.

Now I have a problem where I need to call one method, then another method, so I need a temporary object.

ClassName temp_obj = function1(function2);

temp_obj.method1();
temp_obj.method2();

My question is, how can I declare a temporary object that will store the object that returns by reference. I'm guessing I need a pointer.

The other problem is, temp_obj is contained in a vector, and I'm concerned about conflicts there and memory leakage. If I use a pointer, will I then have to use a destructor also?

Here is the relevant code:

bool Machine::perform_function(std::vector<Job>& jobs) {
    bool add = true;

    if (can_fail) {
        add = coin_toss();

    }

    for (int i = 0; i < my_jobs.size(); i++) {

        if (add) {
            find_job(my_jobs[i], jobs).toggle(name, item_name, true);

        }
        if (!add) {
            find_job(my_jobs[i], jobs).toggle(name, item_name, false);

        }
    }

    return add;
}


Job& Machine::find_job(std::string jobname, std::vector<Job>& jobs) {

    for (int i = 0; i < jobs.size(); i++) {

        if (jobs[i].is_job(jobname)) {
            return jobs[i];

        }
    }
}

Solution

  • It's perfectly fine to store the result as a reference:

    ClassName & temp_obj = function1(function2);
    temp_obj.method1();
    temp_obj.method2();
    

    Your other question here:

    The other problem is, temp_obj is contained in a vector, and I'm concerned about conflicts there and memory leakage.

    It's okay to return jobs[i] as a reference. The operator[] on a vector returns a reference itself. Provided you don't modify the vector in such a way as to change what that reference points at, and you are not storing a reference to an object that has been destroyed, you'll be fine to use it.

    When your temporary reference goes out of scope, nothing happens. It's just a reference.