0

I need to allocate a buffer that is at aligned to a 32 bit boundary (4 bytes).

Will std::make_shared do that? I think it is likely but don't know if it can be guaranteed... as the basic alignment requirement for uchar is one byte.

12
  • std::make_shared<uchar> will not create a buffer anyway, just a shared_ptr on a single uchar. Maybe you want to create an aligned unsigned char array then pass it to the third constructor there? Does your requirement be that you'll store objects all suitably aligned in the buffer? Commented Sep 4, 2024 at 12:59
  • forget the 2nd question as the size (sizeof) of your object must be a multiple of its alignment. Commented Sep 4, 2024 at 13:07
  • The alignment is guaranteed to be at least whatever alignof(uchar) is, whatever that may be. Commented Sep 4, 2024 at 13:47
  • Yes you're right I want to create an array of uchar[] not a single uchar Commented Sep 5, 2024 at 1:43
  • So my guess would be to allocate your buffer with std::aligned_alloc and guive it to std::shared_ptr constructor along with a deleter. Then you can use new-placement to construct your objects inside the buffer (but you'll have to destroy then manually). They are some exception if your objects are implicit-lifetime, trivially-destructible,... or other some nice properties... Commented Sep 5, 2024 at 7:26

1 Answer 1

1

Most implementations of std::make_shared will align a char to a pointer alignment (8 bytes), but it is not guaranteed, And therefore this is not portable.

If you want a portable buffer with a specific alignment then use std::aligned_storage, which must have the correct alignment with make_shared, you can use the overload of make_shared that creates an array of objects if you want to decide the buffer size at runtime, and you want to watch out for the strict aliasing rule when treating it as another type.

As per @TedLyngmo as aligned storage is deprecated in C++23, to make it future-proof you should make your own aligned buffer type

Why is std::aligned_storage to be deprecated in C++23 and what to use instead?

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

3 Comments

I'd create my own aligned storage since std::aligned_storage is/will be deprecated (since C++23).
std::aligned_storage requires to know the buffer size at compile-time. OP didn't tell if it's the case.
@Oersted you can always create an array of these aligned storages, but a vector of the intended type with a custom allocator would be more suitable.

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.