1

Since C++11 there is a dedicated template struct std::aligned_storage and alignas keyword for storing aligned data of any chosen type. I am wondering if it is possible to create portable replacement for std::aligned_storage that is supported in C++03. The only way I imagine this is creating properly aligned (unsigned) char array, but how to align it in a right way is a great unknown for me

2

1 Answer 1

3

It is possible to implement alignof in C++03 for most types, for example there is a long explanation on this page.

With that, you could use a storage type with that alignment using some template specializations:

#include<iostream>

struct alignment {};

template<>
struct alignment<1> {
  typedef char type;
  static const unsigned div_v=sizeof(type);
  static const unsigned add_v=div_v-1;
};
template<>
struct alignment<2> {
  typedef short type;
  static const unsigned div_v=sizeof(type);
  static const unsigned add_v=div_v-1;
};
template<>
struct alignment<4> {
  typedef int type;
  static const unsigned div_v=sizeof(type);
  static const unsigned add_v=div_v-1;
};
template<>
struct alignment<8> {
  typedef double type;
  static const unsigned div_v=sizeof(type);
  static const unsigned add_v=div_v-1;
};

template<typename T>
struct align_store {
  typedef alignment<__alignof(T)> ah;

  typename ah::type data[(ah::add_v + sizeof(T))/ah::div_v];
};

int main() {
  std::cout << __alignof(align_store<int>) << std::endl;
  std::cout << __alignof(align_store<double>) << std::endl;
}
Sign up to request clarification or add additional context in comments.

9 Comments

Alignof may be quite useful, but how does it get me closer to alignas or aligned_storage
Edited my answer - if you know the alignment of the type, you could use a storage type with the same alignment.
It helps me a bit, but I would be thankful if You could give an example of how implement aligned storage having this alignof operator
Without alignas you'll still need a way to get the actual pointer to the memory where your object should live inside your aligned_store.
@Dutow it is not aligned properly. data is large enough to contain the alignment padding followed by an aligned object. But &data will generally not point to a properly aligned memory block in and of itself. Same goes for std::aligned_storage.
|

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.