10

我正在审查自定义容器的代码,它的某些部分创建了如下元素:

::new( (void*)&buffer[index] ) CStoredType( other );

有些人这样做:

::new( &buffer[index] ) CStoredType( other );

因此,两者都使用placement new来调用复制构造函数,通过复制其他元素来创建元素,但在一种情况下,指向新元素存储的指针按原样传递,而在另一种情况下,它被强制转换为void*.

这个演员阵容void*有什么影响吗?

4

2 回答 2

10

是的,您可以为非空指针重载 operator new。强制转换确保采用 void 指针重载。

例如

void* operator new(size_t s, env * e);
于 2011-12-09T09:54:41.857 回答
5

一个可编译的例子:

#include <iostream>
#include <new>

void* operator new(std::size_t, int* x)
{
    std::cout << "a side effect!" << std::endl;

    return x;
}

int main()
{
    int buffer[1];

    new ((void*)&buffer[0]) char;
    new (&buffer[0]) char;
}
于 2011-12-09T10:01:59.160 回答