Best way to return a member variable of a vector to an external class

I am trying to write a LED strip driver in C ++. Now I have a class Stripand Driver; the class Stripabstracts an LED strip with several pixels, and the class Drivercombines the data Stripinto a single buffer for sending over a UDP connection.

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;

serializerecords all pixel data with red-green blue in vector<unsigned char>. Then the driver calls Strip.getPixelData()to get the address mPixelDataand getPixelDataLength()to find out how many bytes are for memcpy().

aggregateStrips() does something like this:

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

, getPixelData()? (shared_ptr?) ? , , ? ( ), memcpy .

!

+4
3

const (std::vector<unsigned char> const &), const, :

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

, .

// 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() . - , const, Strip, .

+6

std::vector , , data(), unsigned char* const unsigned char * , Strip/mBuffer const. ++ 11.

, , const ( ), const - -.

getPixelData() :

const unsigned char* getPixelData() const
{
  return mBuffer.data();
}

, getPixelDataLength() :

std::size_t getPixelDataLength() const
{
  return mBuffer.size();
}

, for(auto strip : Strips) . , , :

for (const auto& strip : Strips) {
  // ...
}
+1

, , (const) :

using PixelIterator = std::vector<unsigned char>::const_iterator;
class Strip {
 ... 
 PixelIterator begin() const {
   return mPixelData.begin();
 }
 PixelIterator end() const {
   return mPixelData.end();
 }
};

memcopy ++, . :

for(const auto& strip : strips)
  mBuffer.insert(mBuffer.end(). strip.begin(),  strip.end());

, auto& , .

, std::vector.

+1

Source: https://habr.com/ru/post/1568216/


All Articles