简体   繁体   English

通过引用返回一个unique_ptr向量

[英]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] . 现在,如果要访问第一个元素,则必须键入(*oi)[0] Whereas if you used a reference, you could just type oi[0] . 而如果您使用引用,则只需键入oi[0]

The extra typing becomes more odious when you want the first int , *(*oi)[0] vs *oi[0] . 当您想要第一个int *(*oi)[0]*oi[0]时,多余的输入变得更令人讨厌。

Starting with: 从...开始:

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

1) dereference the pointer: 1)取消引用指针:

*oi;

2) access first element of vector: 2)访问向量的第一个元素:

(*oi)[0];

3) access int that the unique_ptr points to: 3)访问unique_ptr指向的int:

*((*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. 当似乎需要这样的解决方案时,设计总是存在一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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