A projects to learn the SPI API of the RP2040 C SDK, and to use it to control an external Flash IC. In this post, I refine the m25 c++ class again. take care that an STL container is read-only when passing it to a member.
|
Pass an Array as read-only input parameter
C++ can be used as a strict language. One of the strict options is to flag that an object, passed as reference to a method, will / can not be modified inside the method. The object will have the same state after the execution as before the execution.
class m25 { public: // ... void write(uint32_t address, const std::vector<uint8_t>& data);
In the write() method, the first parameter is passed by value. That is non-mutable by design.
The second parameter is a reference to a vector object. I pass it by reference, to avoid that a copy has to be made of this object. This is a common c++ construct. But that gives the write() the powers to alter the vector or its content.
When you add const in front of the parameter, it's a sign for the compiler that you can only perform calls on that object that don't alter it. When you try to call a modifier (add or change date, empty the container, ...), the compiler will throw an error.
That's it - a small construct that can help avoid that an object is altered. There's more to const. See from page 66 on in Industrial Strength c++.