The C ++ standard defines "undefined behavior" as follows:
for which this standard does not impose requirements
So, if you want your code to be portable for different compilers and platforms, your code should not depend on undefined behavior, since programs (which are produced by different compilers that compile your code) can change in these cases.
If you do not care about portability, then you should check to see if your compiler complies with how it behaves in the circumstances of interest. If he does not document what he is doing (and this is not necessary), be careful that the compiler can change what it is doing without warning between different versions. Also note that its behavior can be non-deterministic. So, for example, this can lead to the collapse of 1% of the time, which you may not notice during special testing, but will come back and bite you later when it starts production. Therefore, even if you use the same compiler, it may still be a bad idea to depend on undefined behavior.
As for your specific example, you can rewrite it to achieve the same effect (without calling the destructor, but fixing the memory) so that it does not lead to undefined behavior. Select a std::aligned_storage
to hold the Foo array, call the new placement to build the Foo array in aligned_storage
, and then when you want to free the array, release aligned_storage
without deleting the placement.
Of course, this is still a terrible design, it might cause a memory leak or other problems depending on what Foo::~Foo()
should have done, but at least it's not UB.
source share