#Is there a function that returns an aligned pointer for some T in a buffer?

26 messages · Page 1 of 1 (latest)

potent wing
#

so, what I need is

char buff [1024]; // alignment is 1
char* start = buff+7;
T* alignedPtr = find_aligned_in_buff<T>(start, buff, 1024); //alignment must be alignof(T), if no such pointer exists after start in the buffer nullptr must be returned

does the standard library have something like this? or do I need to manually make it myself?

whole atlasBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

potent wing
#

this is used to store different variables of type T1, T2, etc... inside a single char buffer of course,
the easy way out would be just to use std::tuple<T1,T2, etc...> and call it a day, but I want to do it manually because std::tuple will call destructors, I do not want to call them immideately

#

hold up... is there a placement aligned operator new ?

eternal scaffold
#

std::align?

potent wing
potent wing
# eternal scaffold std::align?
#include <iostream>
#include <memory>

class alignas(256) Demo
{
    char data[10];
};

int main() {
     char arr[1024] = {};
     
     void* result = arr;
     size_t buffLen = 1024;
    
     bool success = std::align(alignof(Demo), sizeof(Demo), result, buffLen) != nullptr;

    std::cout<<"success? "<<(success ? "yes" : "no")<<"\n";
    std::cout<<"buffer begin = "<<((void*)&arr[0])<<"\n";
    std::cout<<"buffer end = "<<((void*)&arr[1024])<<"\n";
    std::cout<<"aligned result begin: "<<result<<"\n";
    std::cout<<"aligned result end: "<<(void*)((char*)result + buffLen)<<"\n";
    std::cout<<"new buffer length = "<<buffLen<<"\n";
}

is this how it works?

#

it will try to find an address starting from the pointer result ?

#

and adjust result and buffLen accordingly?

ripe stirrup
potent wing
ripe stirrup
whole atlasBOT
#

Thank you and let us know if you have any more questions!

eternal scaffold
potent wing
eternal scaffold
#

the standard specification is actually workable in this case ^^

potent wing
#

it would have been great for my teachers to tell us that this thing exists in C++11 right after they taught us about alignof, but they did not, I had to manually do this from scratch when writing a FirstFit, BestFit and WorstFit memory allocator

#

and also explaining that you are not supposed to do void* + size_t, even though -O3 allows it

eternal scaffold