使用malloc代替new,并在创建对象时调用复制构造函数 [英] Using malloc instead of new, and calling the copy constructor when the object is created

查看:831
本文介绍了使用malloc代替new,并在创建对象时调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试TBB的scalable_allocator,但是当我不得不替换一些代码时感到困惑. 这是使用分配器完成分配的方式:

I wanted to try out TBB's scalable_allocator, but was confused when I had to replace some of my code. This is how allocation is done with the allocator:

SomeClass* s = scalable_allocator<SomeClass>().allocate( sizeof(SomeClass) );

上面显示的不是使用scalable_allocator完成分配的方式.为正确提到了ymett ,分配是这样的:

What's shown above is not how allocation is done with scalable_allocator. As ymett correctly mentioned, allocation is done like this:

int numberOfObjectsToAllocateFor = 1;
SomeClass* s = scalable_allocator<SomeClass>().allocate( numberOfObjectsToAllocateFor );
scalable_allocator<SomeClass>().construct( s, SomeClass());
scalable_allocator<SomeClass>().destroy(s);
scalable_allocator<SomeClass>().deallocate(s, numberOfObjectsToAllocateFor);

这很像使用malloc:

It's pretty much like using a malloc:

SomeClass* s = (SomeClass*) malloc (sizeof(SomeClass));

这是我要替换的代码:

SomeClass* SomeClass::Clone() const
{
   return new SomeClass(*this);
}//Clone

所以尝试了一个程序:

#include<iostream>
#include<cstdlib>
using namespace std;

class S
{
        public:
        int i;
        S() {cout<<"constructed"<<endl;}
        ~S() {cout<<"destructed"<<endl;}
        S(const S& s):i(s.i) {}
};

int main()
{
        S* s = (S*) malloc(sizeof(S));
        s = (S*) S();//this is obviously wrong
        free(s);
}

在这里,我发现调用malloc不会实例化该对象(我以前从未使用过malloc).因此,在弄清楚如何将*this传递给复制ctor之前,我想知道如何在使用malloc时实例化该对象.

and here I found that calling malloc does not instantiate the object (I've never used malloc earlier). So before figuring out how to pass *this to the copy ctor, I'd like to know how to instantiate the object when working with malloc.

推荐答案

malloc获取原始内存后,您需要使用placement new.

You'll need to use placement new after getting the raw memory from malloc.

void* mem = malloc(sizeof(S));
S* s = new (mem) S(); //this is the so called "placement new"

使用完对象后,必须确保显式调用其析构函数.

When you're done with the object you have to make sure to explicitly call its destructor.

s->~S();
free(mem);

这篇关于使用malloc代替new,并在创建对象时调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆