
From: Howard Hinnant
On Jun 14, 2006, at 6:55 AM, David Abrahams wrote:
I think what the OP is looking for is called boost::shared_ptr ;-)
Actually, *one* of my uses is a bit more devious - more like the
short-string optimization - you might want to call it "embedded_ptr
shared_ptr can't compete with this application performance-wise.
Well, it depends how expensive it is to copy your small object. If it turns out that T is a vector, and it fits in your local buffer, when Container is copied it might be a lot cheaper to use shared_ptr.
Sure. I'm responding to the assertion that you need a known complete type to effectively use aligned_storage. My point is that there exist valuable use cases where this assertion is false. The existence of these cases is what makes the defaulted alignment template parameter on aligned_storage valuable.
Tony's observation is that this default value is even more valuable if it is dependent upon the buffer size, which again I fully agree with. If you want a 5 byte buffer that is aligned to the "most stringent alignment requirements" (definition found in 5.3.4p10), an alignment of 16 (for example) is likely to be correct but overkill. I had personally settled on 8 for this particular example but Tony makes a convincing argument for 4 being the optimum (all numbers assuming current popular desktop processors and quoted just for example).
Actually, after thinking about it a bit, I'm now tempted to say a 5 byte
buffer should have 1 byte alignment.
eg (given a typical platform):
struct test_alignment
{
int x;
char y;
};
At first, I thought that any 5 byte structure could have AT MOST a 4 byte
alignment requirement because it could have an int as the first param, as in
the example above. However, if it does have 4 byte alignment, its size will
be 8, so that an array of them will align to 4 bytes. (Howard, you hinted at
this in another email thread).
So,
If sizeof(test_alignment) == 5, then the alignment must really be 1 (ie
there is probably a pragma pack(1) in play).
Either way, the alignment is NOT 16 (or whatever max alignment might be),
but derivable from the size of the structure.
Also, in any case, for boost::type_with_alignment<5> doesn't compile. I
think it should at least do something (or else the standard/docs need to
have lots of wording explaining which ints work and which do not).
Similarly, aligned_storage has the same 'problem' and basically only works
with alignment_of (or something that does the same thing). Since that is
the case anyhow, I would suggest that aligned_storage be replaced with:
storage_for