0

I'm working on one of my class's constructors and it takes a pointer to type. I'm passing in an array of values to this constructor and I'm trying to populate the class's member vector with it. My class looks something like this:

class Foo {
private:
    std::vector<uint32_t> values_;
public:
    Foo( uint32_t* values ) {
        size_t size = sizeof(values) / sizeof(values[0]);
        value_.insert( values_.end(), &values[0], &values[size] );
    }
};

In main I have tried both ways:

int main() {
    uint32_t values[] = { 1,2,3,4,5,6,7,8,9 };
    Foo f( values );
    Foo f( &values[0] );
    return 0;
}

I have used the advise from this answer and it is not working for me. I am only getting a single value in values_. Where am I going wrong and what can I do to fix it?

Francis Cugler
  • 7,788
  • 2
  • 28
  • 59
  • From pointer, you cannot know the size of array. – Jarod42 Nov 08 '18 at 23:33
  • @Jarod okay then; so with this constructor would it require that I pass in the size and use that to index through the array? I am able to change the signature of the constructor. – Francis Cugler Nov 08 '18 at 23:34
  • 1
    `Foo(const uint32_t* values, std::size_t size)` or `template Foo(const uint32_t (&values)[N])`. – Jarod42 Nov 08 '18 at 23:36
  • @Jarod42 That did the trick; with this particular constructor it will require the size of the array to be passed into it making it the callers responsibility to calculate the size of the array that would be passed in as a pointer. Thank You! I knew it was something trivial... might of been just a temporary mental block. – Francis Cugler Nov 08 '18 at 23:39
  • 1
    @FrancisCugler the second example in Jarod42's comment handles fixed-length arrays, so the caller doesn't have to pass the size explicitly. That would allow your `Foo f( values );` example to work as expected. You should implement both constructors, though, so the caller can decide which one to call based on how the array is allocated. In C++11 and later, you can delegate one constructor to the other, otherwise you can delegate them both to an internal helper method, so both constructors share common code to work with whatever input the caller passes in – Remy Lebeau Nov 09 '18 at 06:50

0 Answers0