可以在C ++中优化未使用的数据成员吗 [英] Can unused data members be optimized out in C++

查看:95
本文介绍了可以在C ++中优化未使用的数据成员吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++类,其中有一个未使用的私有char[],严格地将填充添加到该类中,以防止在共享数组中使用该类时出现错误共享.我的问题是2倍:

I have a C++ class which has a private unused char[] strictly to add padding to the class to prevent false sharing when the class is used in a shared array. My question is 2-fold:

  1. 在某些情况下,编译器可以优化此数据成员吗?

  1. Can this data member be optimized out by the compiler in some circumstances?

使用-Wall进行编译时,如何使private field * not used警告静音?最好不要显式地消除警告,因为我仍然想在其他地方捕获此问题的实例.

How can I silence the private field * not used warnings when I compile with -Wall? Preferably, without explicitly silencing the warning as I still want to catch instances of this issue elsewhere.

我写了一个小测试来检查我的编译器,似乎没有删除该成员,但是我想知道标准是否允许这种优化.

I wrote a little test to check for my compiler, and it seems that the member isn't removed, but I want to know if the standards allow this sort of optimization.

#include <iostream>

class A {
 public:
  int a_ {0};

 private:
  char padding_[64];
};

int main() {
  std::cout << sizeof(A) << std::endl;
  return 0;
}

编译

$ clang++ --version
clang version 3.3 (tags/RELEASE_33/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix

$ clang++ -std=c++11 -O3 -Wall padding.cc
padding.cc:8:8: warning: private field 'padding_' is not used [-Wunused-private-field]
  char padding_[64];
       ^
1 warning generated.

$ ./a.out 
68

推荐答案

我不知道编译器的优化,但是您可以通过两种方式摆脱警告:要么使用编译指示:

I don't know about the compiler optimizations, but you can get rid of the warnings in two ways: Either use pragmas:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
class A{
//...
};
#pragma clang diagnostic pop

or(可能更适合您)在您的课程中包括一个伪造的朋友函数:

or, which is probably better suited for you, include a fake friend function in your class:

class A{
friend void i_do_not_exist();
//... 
};

以这种方式,编译器无法知道是否使用了该字段.因此,它不会抱怨,也绝对不会丢掉任何东西.如果在任何地方定义i_do_not_exist()函数,都会导致安全问题,因为该函数可以直接访问该类的私有成员.

In that way, the compiler cannot know if the field is used or not. Therefore, it does not complain and will definitely not throw anything out. This can lead to safety issues if the i_do_not_exist() function is ever defined anywhere, as that function is given direct access to the private members of the class.

第三个解决方案是定义一个访问padding_成员的伪函数:

A third solution is to define a dummy function which access the padding_ member:

class A {
 private:
  void ignore_padding__() { padding_[0] = 0; }
  //... 
};

这篇关于可以在C ++中优化未使用的数据成员吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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