gpt4 book ai didi

c++ - 我什么时候以及为什么要使用-fno-elide-constructors?

转载 作者:太空狗 更新时间:2023-10-29 19:52:21 26 4
gpt4 key购买 nike

我正在学习 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()

如您所见,调用次数存在显着差异。所以我的问题是我什么时候会真正使用这个选项?是否存在此类优化会导致问题的特定情况?我真的想不出我不希望尽可能多地优化我的代码的情况,所以我很难弄清楚这有什么好处。

最佳答案

正如 Benjamin Lindley 对这个问题的评论,如果您的程序依赖于复制构造函数的副作用,那么您的代码编写得非常糟糕。您的复制构造函数应始终编写,以便此类优化是安全的。不仅因为编译器可能会执行此类优化,还因为其他人类读者将很难理解正在发生的事情。

也就是说,该选项仍然很有用。复制构造函数何时被省略是不确定的,看似无关紧要的变化可能会改变复制省略是否发生。因此,-fno-elide-constructors 使 GCC 更具确定性,有时,这有助于调试,因为这意味着您只需添加调试打印语句(作为一个副作用恰好会禁用复制省略)。

您可能想要使用 -fno-elide-constructors 的另一个原因是,如果您希望您的代码在执行较少复制省略的其他编译器上表现良好。如果无用的复制构造函数导致明显的速度下降,您可以重新编写代码,以便无论是否删除拷贝都可以快速运行。

关于c++ - 我什么时候以及为什么要使用-fno-elide-constructors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com