c++ 编译器优化能否在范围结束之前清除未使用的数据结构?
Can c++ compiler optimization clear unused data structures before the scope ends?
考虑以下代码:
#include <set>
template <int n>
std::set<int> utility_function(std::set<int> const & input){
// ...
}
void f(std::set<int> && set1){
std::set<int> set2 = utility_function<1>(set1);
// set1.clear();
std::set<int> set3 = utility_function<2>(set2);
// set2.clear();
std::set<int> set4 = utility_function<3>(set3);
// set3.clear();
// ... use set4, without refering to set1, set2, set3
}
我知道这可能被认为是不好的做法,并且有更好的方法来编写此代码,但假设这是一个 WIP,我只是想在浪费时间进行重构之前让它工作:
理论上编译器是否可以按照评论中的建议清除未使用的数据结构set1
、set2
、set3
(或者只是释放底层内存)?
编译器真的会那样做吗?
根据 as-if 规则,编译器理论上可以删除未使用的数据结构,前提是它可以推断删除它们不会改变程序的语义。为此,编译器必须证明 utility_function
不会将任何集合保留为内部状态的一部分。它还必须证明重新排序构造和破坏不会产生明显的影响。
编译器是否会提前删除数据取决于所涉及的函数,即 f
、utility_function
以及 set
.
的构造函数和析构函数
作为对一个仅隐含陈述的问题的回答,我强烈建议不要依赖特定的优化来保证程序的正确性。如果您需要清除数据集的集合以适合内存,您应该明确地执行此操作。
考虑以下代码:
#include <set>
template <int n>
std::set<int> utility_function(std::set<int> const & input){
// ...
}
void f(std::set<int> && set1){
std::set<int> set2 = utility_function<1>(set1);
// set1.clear();
std::set<int> set3 = utility_function<2>(set2);
// set2.clear();
std::set<int> set4 = utility_function<3>(set3);
// set3.clear();
// ... use set4, without refering to set1, set2, set3
}
我知道这可能被认为是不好的做法,并且有更好的方法来编写此代码,但假设这是一个 WIP,我只是想在浪费时间进行重构之前让它工作:
理论上编译器是否可以按照评论中的建议清除未使用的数据结构set1
、set2
、set3
(或者只是释放底层内存)?
编译器真的会那样做吗?
根据 as-if 规则,编译器理论上可以删除未使用的数据结构,前提是它可以推断删除它们不会改变程序的语义。为此,编译器必须证明 utility_function
不会将任何集合保留为内部状态的一部分。它还必须证明重新排序构造和破坏不会产生明显的影响。
编译器是否会提前删除数据取决于所涉及的函数,即 f
、utility_function
以及 set
.
作为对一个仅隐含陈述的问题的回答,我强烈建议不要依赖特定的优化来保证程序的正确性。如果您需要清除数据集的集合以适合内存,您应该明确地执行此操作。