如何处理clang中的全局构造函数警告? [英] How to deal with global-constructor warning in clang?

查看:594
本文介绍了如何处理clang中的全局构造函数警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clang警告(当使用 -Weverything Wglobal-constructors )关于静态对象的构造函数。 >

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?

简单示例代码:

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

A A::my_A; // triggers said 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.

这是完全合法且安全的C ++。

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.

您可以使用-Wno-global-constructors禁用警告。或者,您可以改为像这样的延迟初始化方案:

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).

这篇关于如何处理clang中的全局构造函数警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆