2016-07-25 37 views
1

嘗試使用佈局新的,但它不斷給我錯誤。我記得前一陣子,它在工作。 Ubuntu 14.04上的g ++(ver 4.8.4)。C++佈局新不斷給編譯錯誤

#include <stdio.h> 
typedef unsigned int uint; 
struct strSession { 
    uint sessionId; 
    uint srcIp; 
    uint dstIp; 
}; 

int main(int argc, char *argv[]) { 
    char buf[20]; 
    strSession *q = (strSession*)&buf[0]; 
    new (q) strSession; 
    return 0; 
} 

遇到錯誤

$ g++ -std=c++11 te.cc `pkg-config --cflags glib-2.0` 
te.cc: In function ‘int main(int, char**)’: 
te.cc:12:10: error: no matching function for call to ‘operator new(sizetype, strSession*&)’ 
    new (q) strSession; 
     ^
te.cc:12:10: note: candidate is: 
<built-in>:0:0: note: void* operator new(long unsigned int) 
<built-in>:0:0: note: candidate expects 1 argument, 2 provided 

任何想法有什麼不對?

回答

6

要使用放置new,你需要有:

#include <new> 

此外,你可以很容易地使用:

int main(int argc, char *argv[]) { 
    char buf[20]; 
    strSession *q = new (buf) strSession; 
    return 0; 
} 
+0

另外我不太明白'q'的意思。似乎擊敗對象。哈哈,可以這麼說。 –

+0

@LightnessRacesinOrbit,同意。 –

+0

需要注意對齊,介意你。 –

1

爲了讓您的原始代碼工作,你需要添加

void* operator new(size_t, strSession * p) { return p; } 

在過去,在C++離開貝爾實驗室之前,C++有一個特性,其中 一個構造函數可以賦值給'this'。運營商新的佈局 語法被認爲是一種改進。