简体   繁体   中英

In C++ struct, what is the difference between default value and default argument in constructor?

for a struct Foo; What is the difference in terms of performance, memory operations, etc between

struct Foo {
 int foo = 1;
};

vs

struct Foo {
Foo(int haha = 1) : foo(haha) {}
int foo;
};

Which is preferred to be used?

There's no true difference.

Every modern compiler (eg, GCC, Clang, MSVC) will optimize away any difference between the two. For instance, this code:

struct Foo {
    int foo = 1;
};

struct Bar {
    int bar;
    Bar(int value = 2) : bar(value) {}
};

void test() {
    auto f = Foo();
    auto b = Bar();
    keep(b);
}

will be compiled to this by GCC with the lowest level optimization (-O1):

test():
        mov     eax, 1  // auto f = Foo();
        mov     eax, 2  // auto b = Bar();
        ret

( Source )

So in both cases, the entire constructor call is optimized away, ending up with a single instruction for each. (Results may vary, but generally the same is the case for each compiler.) There's no performance gain going one way or the other.


My point with this is that there's not really any point in doing this kind level of manual optimization unless you're extremely short on resources, since the compiler is almost always smarter than you and can optimize these things for speed/memory better than you can do by hand.

Instead, you should make your choice based on what you think is the clearest code. That's the only think that makes a true difference here.

It largely depends on your compiler. I put your code into CompilerExplorer and this is what I found: https://godbolt.org/z/5WmOno

They're very similar but the first way is more efficient. In the case of int foo = 1; the value is used directly in the constructor. In the other case, the value is put on the stack by the caller of the constructor even though it is a default value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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