c++中的奇怪语法:return {.name=value,…}
Odd syntax in C++: return { .name=value, ... }
在阅读一篇文章时,我遇到了以下函数:
SolidColor::SolidColor(unsigned width, Pixel color)
: _width(width),
_color(color) {}
__attribute__((section(".ramcode")))
Rasterizer::RasterInfo SolidColor::rasterize(unsigned, Pixel *target) {
*target = _color;
return {
.offset = 0,
.length = 1,
.stretch_cycles = (_width - 1) * 4,
.repeat_lines = 1000,
};
}
作者用return语句做了什么?我以前没有见过这样的东西,我不知道如何寻找它……它对纯C也有效吗?
编辑:链接到原文
这在c++中是无效的。
它(在某种程度上)使用了C语言中被称为"复合字面量"answers"指定初始化器"的两个特性,一些c++编译器将其作为扩展支持。"sort of"来自这样一个事实:要成为一个合法的C复合字面量,它应该具有看起来像强制转换的语法,所以你会有这样的东西:
return (RasterInfo) {
.offset = 0,
.length = 1,
.stretch_cycles = (_width - 1) * 4,
.repeat_lines = 1000,
};
但是,不管语法上的差异如何,它基本上是创建了一个临时结构体,其成员按块中指定的方式初始化,因此这大致相当于:// A possible definition of RasterInfo
// (but the real one might have more members or different order).
struct RasterInfo {
int offset;
int length;
int stretch_cycles;
int repeat_lines;
};
RasterInfo rasterize(unsigned, Pixel *target) {
*target = color;
RasterInfo r { 0, 1, (_width-1)*4, 1000};
return r;
}
这是一个C99复合文字。这个特性是C99特有的,但是gcc和clang也选择在c++中实现它(作为扩展)。
6.26复合字面值ISO C99支持复合文字。复合字面值看起来像A包含初始化式的强制转换。它的值是该类型的对象类型中指定的元素初始化;它是一个左值。作为扩展,GCC支持复合字面量在C90模式和c++中,尽管语义有些不同
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- C++中"dependent name"的定义是什么?
- 为什么我会" void value not ignored as it ought to be"?
- 方法错误"not all control paths return a value"和方法不返回值
- 将系数存储在头文件的数组中("does not name a type"错误)
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 如何在 c++ 中理解这样的代码 [request->headers().Method()->value().getStringView())]
- std::<key-value>不同类型的对向量
- c++ visual studio 64bit | save registers value
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 如何解决类成员函数中的"return a value"错误?
- bsoncxx: document::view vs document::value
- 什么是类型*volatile*name=value
- 如何忽略 doxygen 中的文档'define value name'
- c++中的奇怪语法:return {.name=value,…}
- 为什么"cups_option_t::name"和"::value"不是"const char*"?