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.
auto const&to ensure that. Unlike function declarations, there is no detriment.->or*or.get()on a smart pointer instead of a regular pointer would ever slow the code, as it would be inlined. Nor do I see a person failing to understand a code where a smart pointer is used inside a for-loop in a trivial way. It's like you repeat words without understanding them where they apply.