Base*p=new(buf)Base;的含义是什么;
What is the meaning of Base* p = new(buf) Base;
我最近遇到了一些C++代码,它应该说明valgrind、gdb、insure等中可能出现的许多不同类型的错误。。。
其中一个例子如下:
// =============================================================================
// A base class without a virtual destructor
class Base
{
public:
~Base() { std::cout << "Base" << std::endl; }
};
// Derived should not be deleted through Base*
class Derived : public Base
{
public:
~Derived() { std::cout << "Derived" << std::endl; }
};
// A class that isn't Base
class NotBase
{
public:
~NotBase() { std::cout << "NotBase" << std::endl; }
};
// =============================================================================
// Wrong delete is called. Should call ~Base, then
// delete[] buf
void placement_new()
{
char* buf = new char[sizeof(Base)];
Base* p = new(buf) Base;
delete p;
}
我的问题与以下行有关:
Base* p = new(buf) Base;
我以前从未见过这种语法,在谷歌上搜索了很多次之后,我甚至不知道该搜索什么来找到解释。
有人能给我指正确的方向吗?如果这是多余的或简单的,我深表歉意,但我很好奇这个例子中发生了什么。
谢谢。
这是一个新的布局。它在已经分配的内存上调用构造函数。
通常新的执行2个功能:
-
为对象分配内存
-
通过初始化将内存变成一个对象
placementnew只起到了第二个作用。
它在stl分配器实现中使用了很多。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 文件系统:复制功能的速度秘诀是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- Base*p=new(buf)Base;的含义是什么;