1

Is there any way I can make reference members take no space? For example:

#include <iostream>
#include <glm/glm.hpp>

struct MyClass : public glm::vec3{
  float& rx = x;
  float& ry = y;
  float& rz = z;
};

int main() {
  std::cout << sizeof(glm::vec3) << std::endl;
  std::cout << sizeof(MyClass) << std::endl;
}

the size of the class glm::vec3 is 12 and the size of the class MyClass is 40.

Is there any way I can make the references in MyClass takes no space? Just act as if all codes where ri is used, it is replaced by i?

P.S. If you curious why I'm doing this, I'm adding custom attributes on class members for scanning, but I cannot change third-party codes like glm, that's why I need a wrapper, but if the wrapper is not the same size as the origin one, the space wasted is unacceptable.

3 Answers3

2

Maybe this?

struct MyClass : public glm::vec3{
  float& rx() { return x; }
  float& ry() { return y; }
  float& rz() { return z; }
};

Hard to say from your problem description if that is a possibility.

john
  • 85,011
  • 4
  • 57
  • 81
  • make it inline. than there will be no function at all too. – I S Aug 13 '20 at 07:44
  • I think that's an option, but I need to change my scanning code to search methods as well, currently it just searching fields, I'll do this if I have no choice. Thanks for suggesting. –  Aug 13 '20 at 07:44
  • 4
    @IS, in modern C++ `inline` is not really used to inline anything. A compiler is already smart enough to inline what should be inlined. `inline` is for a linker, and `inline` is not needed here (these member functions are [implicitly inline](https://stackoverflow.com/questions/9192077/is-inline-implicit-in-c-member-functions-defined-in-class-definition)). – Evg Aug 13 '20 at 07:45
2

Reference is an object, if you add it, you make your struct bigger. You can add custom constexpr getters.

#include <iostream>
#include <glm/glm.hpp>

struct MyClass : public glm::vec3
{
  constexpr float& ref_x() { return x; }  
  constexpr float& ref_y() { return y; }  
  constexpr float& ref_z() { return z; }

  // you can also have a nice const overload
  constexpr const float& ref_x() const { return x; }  
  constexpr const float& ref_y() const { return y; }  
  constexpr const float& ref_z() const { return z; }
};

int main() 
{
  static_assert(sizeof(glm::vec3) == sizeof(MyClass));
  std::cout << sizeof(glm::vec3) << std::endl;
  std::cout << sizeof(MyClass) << std::endl;
}
Vasilij
  • 1,861
  • 1
  • 5
  • 9
0

Basically you cant. Every variable has an address on storage and comsume memeory. You can just search variable definition itself. This is from internet.

**A variable definition tells the compiler where and how much storage to create for the variable.**
I S
  • 436
  • 3
  • 7