sizeof(struct) with static const uint8_t [duplicate] - c++

Say I have a class and I have a static member in it, but I don't create any objects of that type. Will the memory be occupied for the static variable? If it would be occupied, what is the point of putting it in a class?

No.
Static members don't belong to the instances of class. They don't increase instances and class size even by 1 bit!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
Output:
1
That is, size of A and B is exactly the same. Static members are more like global objects accessed through A::j.
See demonstration at ideone : http://www.ideone.com/YeYxe
$9.4.2/1 from the C++ Standard (2003),
A static data member is not part of
the subobjects of a class. There is
only one copy of a static data member
shared by all the objects of the
class.
$9.4.2/3 and 7 from the Standard,
once the static data member has been
defined, it exists even if no objects
of its class have been created.
Static data members are initialized
and destroyed exactly like non-local
objects (3.6.2, 3.6.3).
As I said, static members are more like global objects!

The C++ standard doesn't explicitly state when static memory is allocated, as long as it is available on first use. That said, it is most likely allocated during program initialization, thus guaranteeing its presence as soon as it is required, without needing special-case code to detect and perform allocation on access.
The purpose of putting static data into a class is the same as putting any other data into classes. By putting the data into a class structure, you are defining an encapsulating namespace, as well as being able to control access using accessor and mutator methods; this, in turn, will allow you to validate data going into the static memory store, and to ensure consistency throughout the use of this data.

Static variables are stored in a special memory area called BSS, while instances of a class are stored in a heap or on a stack. So, static members are stored separately.

Related

C++: Can I assign the value of non-static member variable to static member variable?

I have a class A in which I have a static member function passName
int A::passName()
{
.... // skip some code
std::string name = ...; // result from codes above
assign(); // this is a static member function in class A
pointerA->passMethodName(name); // pointerA is a class-A static member variable, but of type
// class-B, passMethodName is a class-B non-static member function.
}
The assign function is:
void A::assign(){
pointerA = tempPointerA;
}
Explanation: tempPointerA is a value that is generated during the running process. It is a non-static private class-A member which will be initialized everytime a new object of class A is constructed. But I know in static function I can only use static member directly, so I need to make sure that pointerA is static member. So is assign() function feasible (Or I would rather say, is the whole working principle shown here feasible)?
Thanks for your idea!
No. A static member function can only operate on static variables or call other static functions. (or namespace-scope functions, which are more or less the same as static functions).
ยง9.4.1 [class.static.mfct]
A static member function does not have a this pointer.
So there is no way to access a non-static member variable within a static function.
If you really need assign to remain static, then what you should do is to refactor yourassign()function to accept a variable of typetempPointerA`, and then pass your desired variable in.
int A::passName(B* _in)
{
std::string name = ...; // result from code above
assign(_in); // this is a static member function in class A
_in->passMethodName(name);
}
Otherwise I recommend that you not make it static at all.
Assigning the value will work, but you need to do it from a non-static method (to have access to tempPointerA) or pass the pointer as paramter to the static method. You can access static members from non-static functions (but not the other way around).
What you should pay attention is ownership and destruction. Since you assign the value to a static member the instance can't own the value anymore. Otherwise when the instance is destroyed the static member points to garbage data and you get errors. Also since the static member is never destroyed, your value may leak resources (think DB connection that's never closed).
Also if you are in multi-threaded environment consider if it's possible that multiple threads will attempt to set the value of the static member. You may have the add synchronization. You can also run into race conditions if multiple threads try to initialize the value at the same time.
There is one rule: static functions can't access non-static members and function of the same class without an object. there is no opposite rule. it is because you don't have a this pointer.
You still can declare an object of the same class in the static function and use it's all members, or use any static member.
Therefore from non-static function you can access static functions and members.
If pointerA is static you can access it all. not only to it's static members and functions.

Class static method access to it's static data members

This question is an extension to:
Class method access to it's data members
The take away from the question was that whenever a class method is called, it is implicitely passed the address of the object which helps it access the data members of the class using a 'this*'.
The follow up question is:
How are the static methods of the class able to access the static data members of the class?
The argument remains the same. A function can only access the local variables loaded on the stack.
Are the static data members or their address loaded onto the static function stack implicitely?
If no, how does it work?
The reason is because both are not bound to an instance of that class.
For e.g.
class test
{
public:
static int i=5;
static int getI(){return i;}
};
You can access i like:
int a=test::i;
or like
int a=test::getI();
i is stored in the global data part of the program. It is not bound to an object, therefore it is also identical for every instance created. You can access i without create an instance of class test. class test merely a namespace in this situation. There is no memory magic.

Can a static member of a class as the same type as the class it is member of in C++

lets say I have
class : foo
{
public:
static const foo Invalidfoo;
foo();
foo(int, string);
private:
int number;
std::string name;
};
Is it safe or prone to any problem?
EDIT :
I want to use this to have an invalid object to return as a reference to launch errors.
It is perfectly legal, but the following is better:
class foo:
{
public:
static const& foo Invalidfoo()
{
static foo Invalidfoo_;
return Invalidfoo_;
}
private:
foo();
};
This way you are guaranteed that the object is initialized the first time it is used.
Edit: But no matter how you do it, you still have a global object, and that can be a cause of problem. The best solution may be to call the default constructor each time you need a default constructed object. In terms of efficiency, the difference is probably negligable.
It's legal.
It's actually widely used in the singleton pattern
Singletons multi threading access and creation problems.
A nice article about this:
C++ and the Perils of Double-Checked Locking
It is just acting like a global variable or singleton. It's prone to the problems relating to those.
That is perfectly valid code. It doesn't have any reason to cause any problem, because static data members don't contribute to the size of the class. No matter how many static data members you define in a class, it doesn't change its size by even one byte!
struct A
{
int i;
char c;
};
struct B
{
int i;
char c;
static A a;
static B b;
};
In above code, sizeof(A) == sizeof(B) will always be true. See this demo:
http://www.ideone.com/nsiNL
Its supported by the section $9.4.2/1 from the C++ Standard (2003),
A static data member is not part of
the subobjects of a class. There is
only one copy of a static data member
shared by all the objects of the
class.
You cannot define non-static data member of the enclosing class type, because non-static members are parts of the object, and so they do contribute to the size of the class. It causes problem when calculating the size of the class, due to recursive nature of the data members.
See this topic:
How do static member variables affect object size?
It's legal. Terrible code from a practical/style point of view, but it is legal, and technically, it can be made to work. Better than Singleton because it's immutable.
This is actually how a singleton is implemented, except your static member would be a pointer. So yes, you're safe.

Do static members of a class occupy memory if no object of that class is created?

Say I have a class and I have a static member in it, but I don't create any objects of that type. Will the memory be occupied for the static variable? If it would be occupied, what is the point of putting it in a class?
No.
Static members don't belong to the instances of class. They don't increase instances and class size even by 1 bit!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
Output:
1
That is, size of A and B is exactly the same. Static members are more like global objects accessed through A::j.
See demonstration at ideone : http://www.ideone.com/YeYxe
$9.4.2/1 from the C++ Standard (2003),
A static data member is not part of
the subobjects of a class. There is
only one copy of a static data member
shared by all the objects of the
class.
$9.4.2/3 and 7 from the Standard,
once the static data member has been
defined, it exists even if no objects
of its class have been created.
Static data members are initialized
and destroyed exactly like non-local
objects (3.6.2, 3.6.3).
As I said, static members are more like global objects!
The C++ standard doesn't explicitly state when static memory is allocated, as long as it is available on first use. That said, it is most likely allocated during program initialization, thus guaranteeing its presence as soon as it is required, without needing special-case code to detect and perform allocation on access.
The purpose of putting static data into a class is the same as putting any other data into classes. By putting the data into a class structure, you are defining an encapsulating namespace, as well as being able to control access using accessor and mutator methods; this, in turn, will allow you to validate data going into the static memory store, and to ensure consistency throughout the use of this data.
Static variables are stored in a special memory area called BSS, while instances of a class are stored in a heap or on a stack. So, static members are stored separately.

Will a destructor destroy a static member?

Say I have:
class A
{
A()
{}
~A()
{}
};
class B
{
public:
B()
{}
~B()
{}
private:
static A mA;
};
B* pB = new B;
delete pB;
When I call delete pB, B's destructor will be called. Will this then call the destructor for static member A?
The keyword static means that the variable is independent of instances. That's why you can access static variables and methods without instantiating an object from the class in the first place. That's why destroying an instance will not affect any static variables.
Of course not. First of all, you've defined an explicit empty destructor. And if the default destructor did that, you could never destruct instances without risking making the class unusable.
C++ Standard 03, 9.4.2 Static data members:
A static data member is not part of
the subobjects of a class. There is
only one copy of a static data member
shared by all the objects of the
class.class.
A static data member is not part of the class -- hence it's not tied to the classes lifetime nor at construction or destruction.
Construction (9.4.2/3)
Once the static data member has been
defined, it exists even if no objects
of its class have been created.of its class have been created.
Destruction (9.4.2/7)
Static data members are initialized and destroyed exactly like non-local objects.
Objects with a static lifetime will be destructed when the application terminates. Among the various static objects that might be in the program, the destructors are called in the reverse order of how the objects were constructed.
The construction/destruction of object instances has no effect on when a static member is constructed or destroyed.
Static members do not live in the memory space assigned to an instance of the class. Therefore, it will not be deleted or deinitialized unless you do it explicitly in any part of your code (including the class destructor, but your code logic must handle the possibility of having multiple instances and so on...)
Static variables is also known as class variables. This is as opposed to instance variables. As these names implies, class variables pertain to the entire class, where as instance variables belong to an instance. One can derive the life span of these variables based on these facts.
Another way to look at this assume calling the destructor actually destroys static variables. Imagine then the consequence of one object gets instantiated and then gets deleted. What would happen the the static variables which are shared by all other objects of the class which are still being in used.