简体   繁体   English

C++ 是否优化了对象创建?

[英]C++ Is Object creation optimized out?

If I have a class with two constructors like this:如果我有一个包含两个构造函数的类:

class Test {

    public:

        Test(int x) {
            _num = x;
        }

        Test() {
            _num = 0;
        }

    private:

        int _num;
};

I want to create a stack object based on a condition like this:我想根据这样的条件创建一个堆栈对象:

    Test test;
    if (someCondition() == 23) {
        test = Test(42);
    }

Will I have the overhead of creating a Test object two times, calling both constructors, in this case?在这种情况下,我是否会产生两次创建 Test 对象并调用两个构造函数的开销? Or will this be optimized out in general?或者这会在总体上得到优化吗? Is this considered good practice?这被认为是好的做法吗?

Toy-examples in compiler explorer are optimized heavily with inlining with no apparent constructor call left.编译器资源管理器中的玩具示例通过内联进行了大量优化,没有留下明显的构造函数调用。 So it's not really clear to me.所以我不是很清楚。

Write code to express intent.编写代码来表达意图。

You do not want to call the constuctor twice.您不想两次调用构造函数。 Don't call the constructor twice:不要两次调用构造函数:

Test test = (someCondition() == 23) ? Test() : Test(42);

Can the compiler optimize your code to have only one Test constructed?编译器可以优化您的代码以仅构造一个Test吗?

Yes.是的。 Compiler optimizations must follow the so-called "as-if rule" .编译器优化必须遵循所谓的“as-if rule” In a nutshell: Creating two, one, or none, or 100 instances in your code has no observable effect.简而言之:在您的代码中创建两个、一个、一个或一个或 100 个实例都没有明显的效果。 The compiler can notice that and produce a program where no instance is created.编译器可以注意到这一点并生成一个没有创建实例的程序。

Will the compiler optimize your code to have only one Test constructed?编译器会优化您的代码以仅构造一个Test吗?

You cannot tell unless you try (or you are a compiler writer and your brain is capable of doing the job of a compiler... then you can know without trying).除非您尝试(或者您是编译器编写者并且您的大脑能够完成编译器的工作……然后您无需尝试就可以知道),否则您无法分辨。 That's why it is important to write code to express intent.这就是为什么编写代码来表达意图很重要。 The code you write is not instructions for the CPU, but instructions for the compiler to generate instructions for the CPU.你写的代码不是给CPU的指令,而是让编译器生成给CPU的指令的指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM