【发布时间】:2015-01-21 02:05:30
【问题描述】:
我正在学习 C++,遇到了 -fno-elide-constructors,下面我包含了手册页中的描述。
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a
temporary which is only used to initialize another object of the
same type. Specifying this option disables that optimization, and
forces G++ to call the copy constructor in all cases.
因此,使用此选项,我可以禁用这种特定类型的编译器优化。我有一个程序,它创建 2 个对象并将它们添加在一起并在使用 BASIC4TRACE 库调用每个函数时打印。我编译了相同的程序来测试函数调用的差异,同时使用此选项两次,一次使用,一次不使用,给出此输出。
Without optimizations
BASIC4TRACE: (0x7fff7504a7c0)->Object(const char *)
BASIC4TRACE: (0x7fff7504a7d0)->Object(const char *)
BASIC4TRACE: (0x7fff7504a770)->Object(const char *)
BASIC4TRACE: op+(const Object&, const Object&)
BASIC4TRACE: (0x7fff7504a720)->Object()
BASIC4TRACE: (0x7fff7504a780)->Object(const Object&)
BASIC4TRACE: (0x7fff7504a720)->~Object()
BASIC4TRACE: op+(const Object&, const Object&)
BASIC4TRACE: (0x7fff7504a720)->Object()
BASIC4TRACE: (0x7fff7504a790)->Object(const Object&)
BASIC4TRACE: (0x7fff7504a720)->~Object()
BASIC4TRACE: (0x7fff7504a7f0)->Object(const Object&)
BASIC4TRACE: (0x7fff7504a790)->~Object()
BASIC4TRACE: (0x7fff7504a780)->~Object()
BASIC4TRACE: (0x7fff7504a770)->~Object()
BASIC4TRACE: (0x7fff7504a7e0)->Object(const Object&)
BASIC4TRACE: (0x7fff7504a7f0)->~Object()
BASIC4TRACE: (0x7fff7504a7e0)->~Object()
BASIC4TRACE: (0x7fff7504a7d0)->~Object()
BASIC4TRACE: (0x7fff7504a7c0)->~Object()
With optimizations
BASIC4TRACE: (0x7fffbfc8bbf0)->Object(const char *)
BASIC4TRACE: (0x7fffbfc8bc00)->Object(const char *)
BASIC4TRACE: (0x7fffbfc8bbb0)->Object(const char *)
BASIC4TRACE: op+(const Object&, const Object&)
BASIC4TRACE: (0x7fffbfc8bbc0)->Object()
BASIC4TRACE: op+(const Object&, const Object&)
BASIC4TRACE: (0x7fffbfc8bc10)->Object()
BASIC4TRACE: (0x7fffbfc8bbc0)->~Object()
BASIC4TRACE: (0x7fffbfc8bbb0)->~Object()
BASIC4TRACE: (0x7fffbfc8bc10)->~Object()
BASIC4TRACE: (0x7fffbfc8bc00)->~Object()
BASIC4TRACE: (0x7fffbfc8bbf0)->~Object()
如您所见,拨打的电话数量存在显着差异。所以我的问题是我什么时候会真正使用这个选项?是否存在这种优化导致问题的特定情况?我真的想不出我不希望我的代码尽可能优化的情况,所以我很难弄清楚这有什么好处。
【问题讨论】:
-
当你的程序的正确性依赖于你的拷贝构造函数的副作用时。但是你的程序的正确性不应该依赖于你的拷贝构造函数的副作用。所以,从来没有。除非您试图满足您对编译器行为的求知欲。
-
你可以试试在listserve上提问。
标签: c++ compilation g++ compiler-optimization