deu*_*ost 2 c++ smart-pointers c++17 range-based-loop
在 Herb Sutter 的 2014 年 CppCon 演讲中,他谈到了如果您不打算转让或共享所有权,则不应在函数声明中使用智能指针。最肯定的是,没有对智能指针的 const 引用。
如果我有一个函数接受智能指针指向的元素,那么实现起来就很容易了。你只需这样做:
void f(int& i) //or int*
{
i++;
}
int main()
{
auto numberPtr = std::make_unique<int>(42);
f(*numberPtr);
}
Run Code Online (Sandbox Code Playgroud)
但我想知道,基于范围的循环是否有最佳实践?
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
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法直接捕获当前元素作为引用或原始指针?
对我来说,处理智能指针的引用总是感觉有点不对劲。
只需获取一个引用作为循环中的首要任务for:
for(auto& i : numberPtrVec)
{
auto &n = *i;
Run Code Online (Sandbox Code Playgroud)
n然后在循环的其余部分中使用。