Des*_*tor 1 c c++ compatibility c99 compound-literals
我知道 C 和 C++ 是由不同委员会标准化的不同语言。
我知道像 C 一样,效率从一开始就是 C++ 的主要设计目标。所以,我认为如果任何特性不会产生任何运行时开销,并且它是有效的,那么它应该被添加到语言中。该C99标准有一些非常有用和高效的特性,其中之一是复合文字。我在这里阅读了有关编译器文字的信息。
以下是一个程序,显示了复合文字的使用。
#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;
}
Run Code Online (Sandbox Code Playgroud)
因此,由于使用了复合文字,因此不会创建struct Point注释中提到的额外类型的对象。那么,它是不是很高效,因为它避免了复制对象的额外操作的需要?那么,为什么 C++ 仍然不支持这个有用的特性呢?复合文字有什么问题吗?
我知道一些编译器喜欢g++支持复合文字作为扩展,但它通常会导致不可移植的代码 & 该代码不严格符合标准。是否有任何建议也将此功能添加到 C++ 中?如果 C++ 不支持 C 的任何特性,那么它背后一定有某种原因,我想知道这个原因。
我认为在 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
}
Run Code Online (Sandbox Code Playgroud)