In Herb Sutter's 2014 CppCon talk, he talks about how you shouldn't have smart pointers in your function declaration if you don't intend to transfer or share ownership. And most definitely, no const references to smart pointers.
If I have a function which accepts an element that a smart pointer points to, that's pretty easy to implement. You just do:
void f(int& i) //or int*
{
i++;
}
int main()
{
auto numberPtr = std::make_unique<int>(42);
f(*numberPtr);
}
But what I was wondering, is there a best practice for range-based loops?
int main()
{
auto numberPtrVec = std::vector<std::unique_ptr<int>>{};
for(int i = 0; i < 5; i++)
numberPtrVec.push_back(std::make_unique<int>(i));
for(auto& i : numberPtrVec)
{
//i++; would be the optimum
(*i)++; //dereferencing is necessary because i is still a reference to an unique_ptr
}
}
Is there any way to directly capture the current element as a reference or a raw-pointer?
For me, it always feels a little bit wrong to handle references to smart pointers.
Just grab a reference as the first order of business in the
for-loop:and then work with
nin the rest of the loop.