小编Lea*_*rog的帖子

使用placement new操作符时如何检查是否超出范围?

在下面的代码中

struct alignas(8) SimpleChar {
    SimpleChar(char c_) : c(c_) {}

    char c;
};

int main() {
    char slab[10] = {'\0'};
    // call to 'SimpleChar::SimpleChar(char)' too

    SimpleChar* c0 = new (slab) SimpleChar('a'); 
    SimpleChar* c1 = new (slab + 8) SimpleChar('b');
    SimpleChar* c2 =
      new (std::launder(reinterpret_cast<char*>(slab + 80))) SimpleChar('d');  // But how to detect the wrong usage?
    std::cout << c2->c << std::endl;                                           // d

    SimpleChar* c3 = new (slab + 180) SimpleChar('e');  // But how to detect the wrong usage?
    std::cout << …
Run Code Online (Sandbox Code Playgroud)

c++ valgrind placement-new c++17

2
推荐指数
1
解决办法
167
查看次数

标签 统计

c++ ×1

c++17 ×1

placement-new ×1

valgrind ×1