Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return a vector member variable to external class

I'm trying to write an LED strip driver in c++. Right now I have a Strip class and a Driver class; the Strip class abstracts an LED strip with several pixels, while the Driver class aggregates the Strip data into a single buffer to send over a UDP connection.

The relevant partial classes:

class Strip {
  public:
    ...
    ??? getPixelData();
    int getPixelDataLength();
  protected:
    std::vector<unsigned char> mPixelData;

class Driver {
  public:
    ...
    void aggregateStrips();
  protected:
    vector<unsigned char> mBuffer;

serialize writes all of the red-green-blue pixel data to a vector<unsigned char>. Then the driver calls Strip.getPixelData() to get the address to mPixelData, and getPixelDataLength() to figure out how many bytes to memcpy().

aggregateStrips() does something like this:

int packetLength = 0;
for(auto strip : Strips) {
    memcpy(&mBuffer[packetLength], strip->getPixelData(), strip->getPixelDataLength());
    packetLength += strip.getPixelDataLength();
}

My question is -- what should getPixelData() return? Should it return a smart pointer (shared_ptr?) to the vector? Or perhaps a reference? I only really want the address (and length), because I plan to memcpy it.

thanks!

like image 328
nathan lachenmyer Avatar asked Jan 10 '23 05:01

nathan lachenmyer


1 Answers

Typically you would return a const reference to the vector (std::vector<unsigned char> const &), and in this case you should also make the method const since it doesn't modify the object:

std::vector<unsigned char> const & getPixelData() const;

The caller can decide if they need to make a copy.

// Causes copy-initialization.
std::vector<unsigned char> copy = a_strip.getPixelData();

// Binds a new reference to the existing vector; no copy is made.
std::vector<unsigned char> const & not_a_copy = a_strip.getPixelData();

getPixelDataLength() could also probably be made a const member of the class. Try to make any members that don't change the object const members as it will allow them to be called on Strip objects that are const.

like image 53
cdhowie Avatar answered Jan 17 '23 20:01

cdhowie