Issue
According to the cppreference,
When applied to a reference type, the result is the size of the referenced type.
But in the following program, compiler is giving different output.
#include <iostream>
using namespace std;
class A
{
private:
char ch;
const char &ref = ch;
};
int main()
{
cout<<sizeof(A)<<endl;
return 0;
}
Output:
16
Here ch is of a character type and the reference is also of type character. So output would be 2 bytes instead of 16 bytes.
Online compiler: GDB
Solution
Firstly you're asking for the size of the object, not of the reference type itself.
sizeof(A::ref) will equal 1:
class A
{
public:
char ch;
const char &ref = ch;
};
int main()
{
cout<<sizeof(A::ref)<<endl;
return 0;
}
The object size is 16 because:
- The actual size taken up by the reference type inside the object is equal to the size of a pointer (
8in this case). - Because the object alignment has increased to
8due to the reference type, thecharnow also takes up8bytes even though it only really uses1byte of that space.
I.e. If you were to change char ch to char ch[8], sizeof(A) would still equal 16:
class A
{
private:
char ch[8];
const char &ref = ch[0];
};
int main()
{
cout<<sizeof(A)<<endl;
return 0;
}
Answered By - Tom Clarke Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.