0

i write two pieces of cpp source code, the only difference is one file specify a non-default construction function, while the other one is not:

// code for `test1.cpp`
class Derived {
    private:
        int         non_const_int_val=1;

    public:
        Derived(int a) : non_const_int_val(a) {
        }

} dev(0x2f2f2f2f);

int main() {
    Derived derivedObj(0x55555555), derivedObj_copy(dev);

    return 0;
}
// code for `test2.cpp`
class Derived {
    private:
        int         non_const_int_val=1;

    public:

} dev;

int main() {
    Derived derivedObj, derivedObj_copy(dev);

    return 0;
}

in test2.cpp, the global variable dev will be allocated into .data section, since it is constructed and initialized, and we can verify it as check the elf:

>> objdump -x test2.out | c++filt | grep -E -i "dev"                    
0000000000404028 g     O .data  0000000000000004              dev

While to my surprise, it doesn't hold for test1.cpp and i fail to figure it out (i think it should be initialized as well.): it locates in .bss section.

>> objdump -x test1.out | c++filt | grep -E -i "dev"
000000000040115a l     F .text  0000000000000015              _GLOBAL__sub_I_dev
000000000040402c g     O .bss   0000000000000004              dev

i use g++ with gcc 10.2.0 version.

  • So how can we account for such wired behaviour?
  • Or is there some profound difference between construction and initialization (plz forgive me if i get some core concepts wrong.)?
  • useful references are also preferred.

Thanks.

I dump the elf and pin-point the behavior which confuse me.

0

1 Answer 1

1

In your second snippet, dev is constant initialized. It is initialized by calling a constructor. The default constructor is constexpr, making it a constant expression.

In your first snippet, since your constructor isn't constexpr, it is dynamically initialized. It's zero-initialized and then the actual initializer is run when the program starts (inside ._GLOBAL__sub_I_dev).

If you compile with some optimizations enabled, the compiler should be able to see that dev(0x2f2f2f2f) is essentially a constant and it is allowed to optimize it to be a constant too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.