Quantcast
Channel: User Peter - Reinstate Monica - Stack Overflow
Viewing all articles
Browse latest Browse all 223

Answer by Peter - Reinstate Monica for Pass array to contructor and store in variable

$
0
0

For small arrays, it's probably easiest to simply use std::array (which seems to exist on Arduino) and copy that around. That way, you don't have any lifetime issues. A std::array is basically a regular array wrapped in a struct. It does not dynamically allocate anything — it exists, including all its data, wherever a simple array would exist in its place. It is the data. I can well imagine that copying three bytes around is cheaper than passing pointers or references. Here is an example code (I typedef'd byte and String). Of course, if you have different array lengths, the class Source and any functions taking Source arguments must be templates, but the change will be simple.

#include <iostream>#include <array>using String = const char*;using byte = unsigned char;class Source{public:    Source();    Source(String id, std::array<byte, 3> matrix);    friend void printArr(Source source);private:    String _id;    std::array<byte, 3> _matrix; // <----------};Source::Source() {}Source::Source(String id, std::array<byte, 3> matrix)    : _id{id}, _matrix{matrix}{}void printArr(Source source){    for (auto i : source._matrix)    {        std::cout << (int)i << std::endl;    }}int main(){    Source* src;  // lifetime longer than oriData below    {   // artificially limit original data array lifetime         // to this innner scope        std::array<byte, 3> oriData = { 1,2,3 }; // simple initialization        src = new Source("someId", oriData);    }    // *src has a copy of oriData, lifetime not an issue.    printArr(*src);    delete src;}

The program prints

123

Viewing all articles
Browse latest Browse all 223

Trending Articles