Reputation: 542
I have the following function:
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();
}
This method doesn't actually change vector
, but since it is getting casted I can't make it a const reference. If I use just a reference then cpplint will complain it has to be either const or a pointer.
warning: Is this a non-const reference? If so, make const or use a pointer: std::vector &vector [runtime/references] [2]
Should I just ignore cpplint and make it a reference, keep this code (with the pointer) or make it a const reference and cast a copy?
Upvotes: 2
Views: 1352
Reputation: 28987
As noted in the comments, the correct answer in your case is:
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();
}
However, I think the cpplint error is wrong (this is a matter of opinion of course). I use the rule "if nullptr
is a valid value, use a pointer, otherwise use a reference".
Upvotes: 1