C++的placement new操作

C++的placement new操作

什么是placement new操作
我們知道C++的new操作符會(huì)創(chuàng)建一個(gè)對(duì)象,他完成兩步操作:

  1. 分配對(duì)象內(nèi)存。
  2. 調(diào)用對(duì)象類的構(gòu)造函數(shù)創(chuàng)建對(duì)象。

通常分配的內(nèi)存是在堆中。

但是有些場(chǎng)景下,我們預(yù)先已經(jīng)分配了內(nèi)存,想要在已知的內(nèi)存上創(chuàng)建對(duì)象怎么辦呢?就是說(shuō)我就要一個(gè)對(duì)象創(chuàng)建在這個(gè)內(nèi)存地址,placement new就是實(shí)現(xiàn)這個(gè)目的的。其語(yǔ)法:

Object * p = new (address) ClassConstruct(...)

應(yīng)用場(chǎng)景
在進(jìn)程間使用共享內(nèi)存的時(shí)候,C++的placement new經(jīng)常被用到。例如主進(jìn)程分配共享內(nèi)容,然后在共享內(nèi)存上創(chuàng)建C++類對(duì)象,然后從進(jìn)程直接attach到這塊共享內(nèi)容,拿到類對(duì)象,直接訪問(wèn)類對(duì)象的變量和函數(shù)。

通過(guò)下面的例子來(lái)說(shuō)明:

  1. 主進(jìn)程以server的方式啟動(dòng)
    • 分配共享內(nèi)存
    • 在共享內(nèi)存上通過(guò)placement new創(chuàng)建對(duì)象SHMObj
  2. 從進(jìn)程以普通方式啟動(dòng)
    • attach到主進(jìn)程的共享內(nèi)存
    • 拿到代表SHMObj對(duì)象的指針。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/ipc.h>
#include <sys/shm.h>

#include <new>

#define SHM_KEY 0x3887

class SHMObj {
private:
    int count;
public:
    SHMObj() : count(100) {}
    void increase() { count++; print(); }
    void decrease() { count--; print(); }
    void print() { printf("count=[%d]\n", count); }
};

static int      shm_id = 0;
static void *   shm_addr = NULL;
static SHMObj * shm_object = NULL;

static int attach(bool server) {
    shm_id = shmget(SHM_KEY, sizeof(SHMObj), server ? (IPC_CREAT | 0660) : 0660);
    if (shm_id < 0) {
        printf("ERROR: attach(%d), errno=[%d],strerror=[%s]\n", server, errno, strerror(errno));
        return -1;
    }

    if ((shm_addr = (struct shm_content *)shmat(shm_id, (void *)0, 0)) == NULL) {
        printf("ERROR: attach(%d), errno=[%d],strerror=[%s]\n", server, errno, strerror(errno));
        return -1;
    }

    printf("SUCC: attach(%d), key=[0x%x],id=[0x%x],address=[0x%x],object=[0x%x]\n", server, SHM_KEY, shm_id, shm_addr, shm_object);
}

static int dettach() {
    if (shmdt(shm_addr) != 0) {
        printf("ERROR: dettach(), errno=[%d],strerror=[%s]\n", errno, strerror(errno));
        return -1;
    }

    if (shmctl(shm_id, IPC_RMID, NULL) < 0) {
        printf("ERROR: dettach(), errno=[%d],strerror=[%s]\n", errno, strerror(errno));
        return -1;
    }

    return 0;
}

static int create(bool server) {
    if (server) {
        if ((shm_object = new (shm_addr) SHMObj()) == NULL) {
            printf("ERROR: attach(), errno=[%d],strerror=[%s]\n", errno, strerror(errno));
            return -1;
        }
    }
    else {
        //shm_object = (SHMObj *)(shm_addr);
        shm_object = reinterpret_cast<SHMObj *>(shm_addr);
    }
    printf("SUCC: create(%d), address=[0x%x],object=[0x%x]\n", server, shm_addr, shm_object);
    return 0;
}

static int increase() {
    if (shm_object != NULL) {
        shm_object->increase();
    }
    else {
        printf("ERROR: increase(), call attach firstly\n");
    }
}

static int decrease() {
    if (shm_object != NULL) {
        shm_object->decrease();
    }
    else {
        printf("ERROR: increase(), call attach firstly\n");
    }
}

static int print() {
    if (shm_object != NULL) {
        shm_object->print();
    }
    else {
        printf("ERROR: print(), call attach firstly\n");
    }
}

void help() {
    printf("attach  : \n");
    printf("dettach : \n");
    printf("create  : \n");
    printf("increase: \n");
    printf("decrease: \n");
    printf("print   : \n");
    printf("quit    : quit program\n");
}

int parseCommand(char * cmd, char * argv[]) {
   const char sep[3] = " \n";
   char *token = strtok(cmd, sep);

   int i = 0;
   while (token != NULL) {
      argv[i++] = token;
      token = strtok(NULL, sep);
   }
    return i;
}

int main(int argc, char * argv[]) {
    char cmdbuffer[1024];
    char * cmds[10];    /** max parameters count */
    int i = 0;

    while (1) {
        printf("CMD> ");
        fgets(cmdbuffer, 1024, stdin);
        i = parseCommand(cmdbuffer, cmds);
        if (i > 0) {
            if (strcmp(cmds[0], "quit") == 0) {
                break;
            }
            else if (strcmp(cmds[0], "attach") == 0) {
                    attach(argc > 1 && strcmp(argv[1],"server") == 0);
            }
            else if (strcmp(cmds[0], "dettach") == 0) {
                    dettach();
            }
            else if (strcmp(cmds[0], "create") == 0) {
                    create(argc > 1 && strcmp(argv[1],"server") == 0);
            }
            else if (strcmp(cmds[0], "increase") == 0) {
                    increase();
            }
            else if (strcmp(cmds[0], "decrease") == 0) {
                    decrease();
            }
            else if (strcmp(cmds[0], "print") == 0) {
                    print();
            }
            else if (strcmp(cmds[0], "help") == 0) {
                help();
            }
            else {
                printf("unknown command: %s\n", cmds[0]);
            }
        }
    }
    return 0;
}

運(yùn)行
主進(jìn)程:

$ ./main server
CMD> attach
SUCC: attach(1), key=[0x3887],id=[0x1a8004],address=[0xe7b59000],object=[0x0]
CMD> create
SUCC: create(1), address=[0xe7b59000],object=[0xe7b59000]
CMD> print
count=[100]
CMD> increase
count=[101]
CMD> increase
count=[102]
CMD> print
count=[102]
CMD> 

從進(jìn)程:

$ ./main 
CMD> attach
SUCC: attach(0), key=[0x3887],id=[0x1a8004],address=[0xa1126000],object=[0x0]
CMD> create
SUCC: create(0), address=[0xa1126000],object=[0xa1126000]
CMD> print
count=[102]
CMD> 

從這個(gè)例子我們看到對(duì)象shm_object在主進(jìn)程里面被創(chuàng)建(placement new),但是在從進(jìn)程里面并沒(méi)有創(chuàng)建,而是直接從共享內(nèi)存里面解析出來(lái),然后直接訪問(wèn)類成員和函數(shù)。
需要注意的是,創(chuàng)建出來(lái)的對(duì)象的地址就是共享內(nèi)存的地址,就是基于這個(gè)屬性,我們的功能才能實(shí)現(xiàn)。也就是說(shuō):

Object * p = new (address) ClassConstruct(...)

返回p的值,和輸入地址address的值是相同的。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容