到目前为止,为什么复合文字不是C ++的一部分?

时间:2016-02-14 10:29:12

标签: c++ c compatibility c99 compound-literals

我知道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的任何特性,那么它背后必然有一些原因。我想知道这个原因。

1 个答案:

答案 0 :(得分: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
}
相关问题