MSVC 中的复合文字

2021-12-14 00:00:00 gcc c struct c++ visual-studio-2010

在 GCC 中,我可以这样做:

In GCC, I'm able to do this:

(CachedPath){ino}
inode->data = (struct Data)DATA_INIT;

哪里:

struct CachedPath
{
    Ino ino;
};

typedef int8_t Depth;
struct Data
{
    Offset size;
    Blkno root;
    Depth depth;
};
#define DATA_INIT {0, -1, 0}

MSVC 为这些类型的转换提供以下错误:

MSVC gives the following error for these kind of casts:

error C2143: syntax error : missing ';' before '{'

如何在 MSVC 中执行此操作? 进一步注意,代码已从 C99 转换而来,我为此使用了指定的初始值设定项,然后进行了类似的转换.任何有关 C99 和 C++ 的 MSVC/GCC 实现之间的各种功能之间关系的清晰性表示赞赏.

How can I do this in MSVC? Further note that the code has been converted from C99, where I used designated initializers for this, and then cast it similarly. Any clarity on how these various features relate between C99, and MSVC/GCC implementations of C++ is appreciated.

推荐答案

构造 (Type){initialisers} 不是强制转换操作,而是复合的句法构造字面意思.这是一个 C99 构造,GCC 在其 C++ 编译器中也支持它作为扩展.据我所知,在 C 或 C++ 模式下,直到并包括 MSVC 2012 都不支持复合文字.对 C 模式的支持是后来在 MSVC 2013 中引入的.在 C++ 模式下仍然不支持,我认为不太可能会添加支持.

The construct (Type){initialisers} is not a cast operation, but it is the syntactic construct of a compound literal. This is a C99 construct, which GCC also supports in its C++ compiler as an extension. As far as I can determine, compound literals are not supported up to and including MSVC 2012, in either its C or C++ mode. The support in C mode was introduced later, in MSVC 2013. In C++ mode it is still not supported and I believe it is unlikely support will be added.

对于 MSVC 2012 及更早版本,此构造的替代方案是

For MSVC 2012 and older, the alternatives for this construct are

  • 显式声明和初始化所需结构类型的临时对象,并在赋值中使用它而不是复合字面量
  • 不要对复合文字进行单一赋值,而是为每个单独的成员使用单独的赋值.

相关文章