简体   繁体   中英

Returning a vector of unique_ptr by reference

Here is my code

class Carl{
    public:
    std::vector<std::unique_ptr<int>> asd;
    Carl(){
        asd.push_back(std::unique_ptr<int>(new int(4)));
        asd.push_back(std::unique_ptr<int>(new int(2)));
    }

    std::vector<std::unique_ptr<int>> & getVec(){
        return asd;
    }
};



int main(int argc, char** argv) {
    Carl v; 
    std::vector<std::unique_ptr<int>> * oi = &(v.getVec());

    //how to print first element?
    return 0;
}

My goal is to access the unique pointer w/o giving up the ownership.

My question is that, if I return by reference and catch the reference's address by using a vector pointer, will it work?

I know that receiving by reference will work better, but i am trying to find out if it's possible to receive by pointer.

Yes, this code is perfectly valid:

std::vector<std::unique_ptr<int>> * oi = &(v.getVec());

It's also unnecessarily confusing. Now if you want to access the first element, you'd have to type (*oi)[0] . Whereas if you used a reference, you could just type oi[0] .

The extra typing becomes more odious when you want the first int , *(*oi)[0] vs *oi[0] .

Starting with:

std::vector<std::unique_ptr<int>> * oi

1) dereference the pointer:

*oi;

2) access first element of vector:

(*oi)[0];

3) access int that the unique_ptr points to:

*((*oi)[0]);

The above should work, but I do not think it is a good solution. There is almost always something wrong with the design when such a solution seems necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM