[PATCH] D23385: Implement __has_constant_initializer(obj) expression traits.

Eric Fiselier via cfe-commits cfe-commits at lists.llvm.org
Wed Aug 10 17:04:44 PDT 2016


EricWF created this revision.
EricWF added reviewers: aaron.ballman, rsmith, majnemer.
EricWF added a subscriber: cfe-commits.

Safe static initialization is hard to do correctly in C++.  The static initialization order fiasco often causes bugs when variables are dynamically initialized. However some variables are 'constant initialized', which guarantees they will not have these issues. Unfortunately there is no easy way to check if 'constant initialization' actually takes place.

This patch adds a `__has_constant_initializer(<expr>)`  expression trait, which returns 'true' if `<expr>` names a VarDecl which has a constant initializer.
`__has_constant_initializer(<expr>)` requires `<expr>` be a DeclRefExpr, Anything else is diagnosed as a usage error.

Example Usage:
```
struct NonLit {
  constexpr NonLit(int x) : value(x) {}
  ~NonLit() {}
  int value;
};
NonLit global_obj = 42;
static_assert(__has_constant_initializer(global_obj), "dynamic initialization is not acceptable!");
```

https://reviews.llvm.org/D23385

Files:
  include/clang/AST/Expr.h
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Basic/ExpressionTraits.h
  include/clang/Basic/TokenKinds.def
  lib/AST/Expr.cpp
  lib/AST/StmtPrinter.cpp
  lib/Parse/ParseDeclCXX.cpp
  lib/Parse/ParseExpr.cpp
  lib/Parse/ParseExprCXX.cpp
  lib/Sema/SemaExprCXX.cpp
  test/SemaCXX/expression-traits.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D23385.67632.patch
Type: text/x-patch
Size: 17743 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20160811/35fa8c79/attachment-0001.bin>


More information about the cfe-commits mailing list