Reputation: 2823
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.
Upvotes: 0
Views: 955
Reputation: 303117
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]
.
Upvotes: 1
Reputation: 7985
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.
Upvotes: 1