【问题标题】:pass vector by reference or by pointer通过引用或指针传递向量
【发布时间】:2017-11-10 13:28:24
【问题描述】:

我有以下功能:

void write_to_File(std::vector<uint16_t> *vector) {
    std::fstream file;
    file.open(writePath, std::fstream::out | std::fstream::binary);
    if (file.is_open()) {
         file.write(reinterpret_cast<char*>(&(*vector)[0]), vector->size()*sizeof(uint16_t));
    } else {
        std::cout << "file not found!";
        return;
    }
    file.close();
}

这个方法实际上并没有改变vector,但是由于它被强制转换,我不能让它成为一个常量引用。如果我只使用一个引用,那么 cpplint 会抱怨它必须是 const 或指针。

警告:这是一个非常量引用吗?如果是这样,请使用 const 或使用指针:std::vector &vector [runtime/references] [2]

我应该忽略 cpplint 并将其设为引用,保留此代码(使用指针)还是将其设为 const 引用并转换副本?

【问题讨论】:

  • 通过 const 引用传递。你可以投到const char*
  • @juanchopanza 我会因为没有想到这一点而将头撞到墙上,谢谢。
  • 你没有使用指针中固有的任何东西,通过引用传递。
  • [OT]:注意字节顺序问题。

标签: c++ pointers vector reference


【解决方案1】:

如 cmets 所述,您的正确答案是:

void write_to_File(const std::vector<uint16_t>& vector) {
    std::fstream file;
    file.open(writePath, std::fstream::out | std::fstream::binary);
    if (file.is_open()) {
         const auto ptr = reinterpret_cast<const char*>(&vector[0]);
         file.write(ptr, vector.size()*sizeof(uint16_t));
    } else {
        std::cout << "file not found!";
        return;
    }
    file.close();
}

但是,我认为 cpplint 错误是错误的(这当然是见仁见智)。我使用规则“如果nullptr 是有效值,则使用指针,否则使用引用”。

【讨论】:

  • const auto ptr 有必要吗?此外,您的代码包含语法错误,(*vector) 应该只是 vector,因为它不再是指针,与 -&gt; 相同
  • @Arrow - 不,const auto ptr 不是必需的 - 只是没有它,我会得到水平滚动条,并且我讨厌水平滚动条。我也碰巧认为代码更容易阅读,因为它区分了“计算数据在哪里”和“将数据写入磁盘”(但 YMMV)。 (修复语法错误当然必要的!- 并且完成了。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2014-07-27
  • 2023-03-03
相关资源
最近更新 更多