简体   繁体   中英

Why are compound literals not part of C++ so far?

I know that C & C++ are different languages standardized by different committees.

I know that like C efficiency has been a major design goal for C++ from the beginning. So, I think if any feature doesn't incur any runtime overhead & if it is efficient then it should be added into the language. The C99 standard has some very useful & efficient features and one of them is compound literals . I was reading about compiler literals here .

Following is a program that shows the use of compound literals.

#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;
}

So, due to the use of compound literals there is no creation of an extra object of type struct Point as mentioned in the comments. So, isn't it efficient because it avoids the need for an extra operation copying objects? So, why does C++ still not support this useful feature? Are there any problems with compound literals?

I know that some compilers like g++ support compound literals as an extension but it usually leads to unportable code & that code isn't strictly standard conforming. Is there any proposal to add this feature to C++ also? If C++ doesn't support any feature of C there must be some reason behind it & I want to know that reason.

I think that there is no need for compound literals in C++, because in some way, this functionality is already covered by its OOP capabilities (objects, constructors and so on).

You program may be simply rewritten in C++ as:

#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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM