When and why would I use -fno-elide-constructors?

强颜欢笑 提交于 2019-12-04 12:13:16

As Benjamin Lindley commented on the question, if your program relies on the side effects of copy constructors, your code is very badly written. Your copy constructors should always be written so that such optimisations are safe. Not only because the compiler may perform such optimisations, also because other human readers will otherwise have a very hard time understanding what is going on.

That said, the option can still definitely be useful. Exactly when copy constructors are elided is unspecified, and seemingly irrelevant changes may change whether copy elision happens. Thus, -fno-elide-constructors makes GCC more deterministic, and sometimes, that helps in debugging, as it means you can worry less about code that starts working just by adding debug print statements (which as a side effect happen to disable copy elision).

Another reason you may want to use -fno-elide-constructors is if you want your code to perform well on other compilers that perform less copy elision. If the useless copy constructors cause a noticeable slowdown, you can re-work the code so that it's fast regardless of whether copies get elided.

An example comes from a rtti (Real Time Type Information). If Your program is using the typeid() function, then it relies for the type to be instantiated. An example is the One Definition Rule:

class mesh; // Forward (incomplete) declaration

if(property.type() == typeid(mesh*)) // Crash here in typeid()
{
   // do something
}

Now imagine a slightly more sophisticated example, where Your class is templated:

template <class T0> class mesh { };

if(property.type() == typeid(mesh<T>*))
{
   // do something
}

Even though the class is fully declared, the class may never be used, thus, never be instantiated. In this case the only way to avoid segfault is to disable the optimization and that way the class will always be instantiated, and thus produces a correct typeid.

A real-world example can be found by compiling the sample code from SymboliC++.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!