Can placement new survive optimization, unlike memset?

So I'm really intrigued about whether or not it can survive aggressive optimization tactics employed by GCC and clang.

Considering the following example:

void* clean(void* pointer, std::size_t size) noexcept
{
    return new(pointer) char[size]{};
}

void doStuff()
{
    //...
    clean(pointer, size);
    //...
}

Can I trust it with the task of cleaning sensitive data?


I do not think optimization can play any tricks on you here. Standard mandates value initialization in this case: new(pointer) char[size]{} , so after this call memory pointed to by pointer would be filled with 0.

May be compiler can optimize it if you never access the new pointer or override it before accessin (based on observability). If you want to avoid this slight possibility, you'd need to define your pointer as a pointer to volatile .


I am not sure whether this is an answer to your question or just a side note but you can disable optimization on that specific function using optimize() compiler directive

void* __attribute__((optimize("O0"))) clean(void* pointer, std::size_t size) {
    // unmodifiable compiler code
}

This will ensure your clean() function will not be optimized away

链接地址: http://www.djcxy.com/p/90570.html

上一篇: 如何防止Parse保存PFObject儿童?

下一篇: 与memset不同,可以放置新的优化吗?