This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Using pure and const attributes for Meyers' singleton


Just adding some relevant links (I don't claim they answer your question)

https://stackoverflow.com/questions/49326293/does-meyers-singleton-used-with-gnupure-have-ub
https://gcc.gnu.org/ml/gcc/2012-10/msg00024.html

On Wed, 4 Apr 2018, Antons.Jelkins@bmw.de wrote:

Hello,

GCC has const and pure function attributes as described here:
https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

The attributes' specification is not as technical as the C++ standard, but their purpose seems to be to allow a compiler to call functions annotated with const or pure less than a program code says. The specs also say that such functions must not have any effects except their return value and the return value must depend only on function arguments and/or (in case of "pure") global variables.

Assume, there is such Meyers' singleton:

class MyClass
{
public:
   MyClass();
};

[[ gnu::const ]]
static const MyClass &myClass()
{
   static MyClass s_myClass;
   return s_myClass;
}

Can const and pure attributes be used here? On the one hand, the singleton function does not have any observable effects other than its return value and it always returns the same value. So it is completely safe to optimise away multiple calls to this function. On the other hand, this function needs to construct the MyClass object on the first invocation. This includes calling a MyClass constructor and setting an implicit is-initialised flag to true. It also must be thread-safe. This could count as an effect besides the return value (although it is not visible from the outside).

void doThis(const MyClass&);
void doThat(const MyClass&);

void foo()
{
   doThis(myClass());
   doThat(myClass());
}

GCC *does* optimise away the second call to myClass(). My question would be if this is an expected and desired behaviour which I can rely on, or this is a coincidence?

Clang clearly treats this code as invalid, but they might change their behaviour if there is evidence that GCC implements a different rule:
https://bugs.llvm.org/show_bug.cgi?id=36750

Regards,
Anton

--
Marc Glisse


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]