Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c++ - How to deal with global-constructor warning in clang?

Clang warns (when using -Weverything or Wglobal-constructors) about constructors for static objects.

warning: declaration requires a global constructor
      [-Wglobal-constructors]
A A::my_A; // triggers said warning
     ^~~~

Why is this relevant and how should one deal with this warning?

Simple example code:

class A {
  // ...
  static A my_A;
  A();
};

A A::my_A; // triggers said warning
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a simpler case that triggers the same warning:

class A {
public:
  // ...
  A();
};

A my_A; // triggers said warning


test.cpp:7:3: warning: declaration requires a global constructor [-Wglobal-constructors]
A my_A; // triggers said warning
  ^~~~
1 warning generated.

This is perfectly legal and safe C++.

However for every non-trivial global constructor you have, launch time of your application suffers. The warning is simply a way of letting you know about this potential performance problem.

You can disable the warning with -Wno-global-constructors. Or you can change to a lazy initialization scheme like this:

A&
my_A()
{
    static A a;
    return a;
}

which avoids the issue entirely (and suppresses the warning).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...