2016-02-14 26 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

相关问题