2016-02-14 29 views
0

我知道C++是由不同委員會標準化的不同語言。爲什麼複合文字到目前爲止不是C++的一部分?

我知道,從一開始就像C效率一直是C++的主要設計目標。所以,我認爲如果任何功能不會產生任何運行時間開銷&如果它是有效的,那麼它應該被添加到語言中。 C99標準有一些非常有用的&高效功能,其中之一是複合文字。我正在閱讀有關編譯器文字here

以下是顯示覆合文字使用的程序。

#include <stdio.h> 

// Structure to represent a 2D point 
struct Point 
{ 
    int x, y; 
}; 

// Utility function to print a point 
void printPoint(struct Point p) 
{ 
    printf("%d, %d", p.x, p.y); 
} 

int main() 
{ 
    // Calling printPoint() without creating any temporary 
    // Point variable in main() 
    printPoint((struct Point){2, 3}); 

    /* Without compound literal, above statement would have 
     been written as 
     struct Point temp = {2, 3}; 
     printPoint(temp); */ 

    return 0; 
} 

因此,由於使用複合文字的沒有創作爲在評論中提到struct Point類型的額外的對象。那麼,效率不高,因爲它避免了需要額外的操作複製對象?那麼,爲什麼C++仍然不支持這個有用的功能?複合文字有沒有問題?

我知道像g++這樣的編譯器支持複合文字作爲擴展名,但它通常會導致代碼不嚴格符合標準的不可移植代碼&。有沒有提議將此功能添加到C++?如果C++不支持C的任何功能,那麼肯定會有一些原因&我想知道這個原因。

+6

'printPoint({2,3});'將用C++工作(> = C++ 11我認爲) – Mat

+0

@Mat:是肯定。見http://melpon.org/wandbox/permlink/UfxN5SQ5HUQhuAIj。我想你正在討論C++ 11引入的新括號初始化語法。 – Destructor

+0

誰投票關閉和爲什麼?我的問題出了什麼問題? – Destructor

回答

4

我認爲在C++中不需要複合文字,因爲在某些方面,這個功能已經被其OOP功能(對象,構造函數等)所覆蓋。

您程序可以用C簡單地改寫++爲:

#include <cstdio> 

struct Point 
{ 
    Point(int x, int y) : x(x), y(y) {} 
    int x, y; 
}; 

void printPoint(Point p) 
{ 
    std::printf("%d, %d", p.x, p.y); 
} 

int main() 
{ 
    printPoint(Point(2, 3)); // passing an anonymous object 
} 
+2

如果你使用C++ 14並使用大括號初始化,那麼你也會得到幾乎相同的語法。 – StoryTeller

+1

@StoryTeller:你的意思是[C++ 11](http://en.cppreference.com/w/cpp/language/list_initialization)? – Michael

+1

@邁克爾,不,我的意思是我說的。除了不充分的comiler支持,沒有理由避免C++ 14,因爲它包含了一些改進 – StoryTeller

相關問題