1

I am trying to implement a fixed size array of 32 bit integers, but the size is determined at runtime so it has to be heap allocated. Would it be more efficient to use a c++ std::vector and use vector.reserve() or should I use the conventional way of doing it using new int32_t[size]? Additionally, would it be worth using a unique_ptr with the conventional method using new?

5
  • 2
    Start with std::vector. If it turns out to be the wrong choice, unlikely, you'll find out when profiling the code. Commented May 21, 2022 at 17:28
  • 2
    Sidenote: Don't use new with unique_ptr unless you have really strange requirements. Prefer std::make_unique. Commented May 21, 2022 at 17:29
  • 2
    Side-side note: reserve allocates storage, but it doesn't set up vector to fully use it. If you want the usual array-style behaviour with [] access, you want to use resize or one of the constructors that specifies an initial size. reserve is mostly used when you want to avoid unnecessary reallocations when you're inserting elements into the vector. Commented May 21, 2022 at 17:35
  • 3
    std::unique_ptr is aware of arrays and delete[]. You can use use std::unique_ptr<int[]> as a safe pointer to a dynamically allocated array and std::make_unique<int[]>(n); to dynamically create an array of size n equivalent to new int[n];. auto ptr = std::make_unique<int[]>(10); is a safe equivalent to auto ptr = new int[10];. Don't use std::unique_ptr<int> to refer to an array as the wrong delete will be used on destruction. Commented May 21, 2022 at 17:42
  • Note: If you are intentionally trying to avoid value initialization, you cannot use std::make_unique Commented Jan 21, 2023 at 17:13

1 Answer 1

3

You would just be re-implementing std::vector. Probably badly because it takes years to figure out all the little corner cases and implement them correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.