C++ static members - c++

I have the following code:
void Foo() {
static std::vector<int>(3);
// Vector object is constructed every function call
// The destructor of the static vector is invoked at
// this point (the debugger shows so)
// <-------------------
int a;
}
Then somewhere I call Foo several times in a sequence
Why does the vector object gets constructed on every Foo() call and why is the destructor called right after static ... declaration?
Update:
I was trying to implement function once calling mechanism and I thought that writing something like
static core::CallOnce(parameters) where CallOnce is a class name would be very nice.
To my mind writing static core::CallOnce call_once(parameters) looks worse, but okay, this is the case I can't do anything with it.
Thank you.

Your variable needs a name:
static std::vector<int> my_static_vector(3);

You forgot to give the vector a name, so without any variable pointing to it it's destroyed immediately after it's created

Because std::vector<int>(3) creates an unnamed temporary, which lives only to the end of it's contained expression. The debugger can't show destruction in the same line as construction though, so it shows it on the next line.
Give the item an name and normal static semantics will apply.

Related

How does ones code access member variables in a different stack frame

class foo {
public:
foo() : foo_member1(1)
int foo_member1;
void do_something() {foo_member1++;}
}
int main(){
foo my_foo;
my_foo.do_something();
}
Where is everything stored in the above example code? It was something I thought of whilst driving home and was embarrassed that I couldn't answer for certain.
I create an object containing a variable both on the stack. When I call do_something and enter a new stack frame how does it have access to the member variable which was stored in the previous stack frame as part of the my_foo object? Is it copied in? Passed through silently underneath by reference? Or does it actually end up on the heap? Or is there some special mechanism by which code can access something that precedes it in the stack?
This:
my_foo.do_something();
Calls the method foo::do_something() by passing a hidden parameter this = &my_foo. This is just a regular C function that simply gets a hidden parameter. The code of do_something does not really access the stack frame of main, it simply uses this that main passed.
Inside of do_something, the code is treated as:
this->foo_member1++;
No cross-frame access. It is just a pointer to a memory location, that happens to be in main's frame. There is no memory protection when passing pointers between functions.

if I return a class in my function, where does it store?

look at my code:
#include <iostream>
using namespace std;
class MyClass{
public:
char ch[50] = "abcd1234";
};
MyClass myFunction(){
MyClass myClass;
return myClass;
}
int main()
{
cout<<myFunction().ch;
return 0;
}
i can't understand where my return value is stored? is it stored in stack? in heap? and does it remain in memory until my program finished?
if it be stored in stack can i be sure that my class values never change?
please explain the mechanism of these return. and if returning structure is different to returning class?
MyClass myClass; is stored on the stack. It's destroyed immediately after myFunction() exits.
When you return it, a copy is made on the stack. This copy exists until the end of the enclosing expression: cout << myFunction().ch;
Note that if your compiler is smart enough, the second object shouldn't be created at all. Rather, the first object will live until the end of the enclosing expression. This is called NRVO, named return value optimization.
Also note that the standard doesn't define "stack". But any common implementation will use a stack in this case.
if returning structure is different to returning class?
There are no structures in C++; keyword struct creates classes. The only difference between class and struct is the default member access, so the answer is "no".
It's up to the implementation to find a sensible place to store that value. While it's usually on the stack, the language definition does not impose any requirements on where it's actually stored. The returned value is a temporary object, and it gets destroyed at the end of the full statement where it is created; that is, it gets destroyed at the ; at the end of the line that calls myFunction().
When you create an object in any function it's destroyed as soon as the function execution is finished just like in variables.
But when you return a object from a function firstly compiler creates a local instance of this object in heap called unnamed_temporary then destroyes the object you created. And copies the contents of unnamed_temporary on call. Then it destroyes this unnamed _temporary also.
Anything you create without the keyword new will be created in stack.
Yes,contets of your variable ch will not change unless you access that variable and change it yourself.
The instance returned by myFunction is temporary, it disappears when it stop to be useful, so it doesn't exist after after the cout <<.... Just add a destructor and you will see when it is called.
What do you mean about can i be sure that my class values never change? ? You get a copy of the instance.
returning structure is different to returning class? : a struct is like a class where all is public by default, this is the alone difference.
Your function is returning a copy of an object. It will be stored in the stack in memory.
The returning obj. will exist until the scope of that function. After that, it will be destroyed. Then, your expression cout<<function(); will also have the copy of that obj. which is returned by the function. IT will be completely destroyed after the running of this cout<<function(); expression.

When does a constructor of a class with static members runs in C++?

I'm new to c++ so i don't know much about it yet
so basically i have this code
header file
class Application{
public:
static Application& getInstance()
{
return *mInstance;
}
Application();
void run();
protected:
static Application* mInstance;
source file
Application* Application::mInstance;
Application::Application()
{
mInstance = this;
}
then i do
Application::getInstance().run();
When does the constructor for Application class runs?
It seems to work in visual studio.
So my question is why does this work?
Why does getInstance does not return a null pointer? since i have never instantiated the class.
Is this code standard?
will this work on any modern c++ compiler?
The constructor of a class belongs to an object, i.e. if it is called explicitly by the code somewhere it creates an object in the memory (on the stack or on the heap). So if you do not call the constructor somewhere it is never executed.
I see only the point why this can run is that you did not specify the initial value of the mInstance pointer. This means that its value is undefined and accidentally can have some valid address. If the run() method does not touch the mInstance object itself your code can run sometimes but sometimes not. This is the problem of uninitialized variables in C++.
But I suggest to follow the right singleton pattern:
1. Initialize mInstance as a nullptr.
2. The getInstance() function should call the constructor if mInstance is nullptr.
(Just a general hint: Avoid passing this in constructor to somewhere else because at that point the object is not fully constructed and in case of multi-thread application it can cause issues.)
The constructor is executed whenever an object is constructed.
Static objects at file scope are constructed before calling main(). However, if you are relying on order of construction of two such static objects (e.g. construction of one relies on the other already being constructed) you potentially have a problem. The order of construction of statics defined in two distinct compilation units (aka source files) is unspecified.
Static objects that are local (e.g. to a function) are constructed as control passes through their declaration .... typically as their function is called for the first time.

Global variable inside cpp file

I have a global variable inside an anonymous namespace.
namespace {
std::unordered_map<std::string, std::string> m;
}
A::A() { m.insert(make_pair("1", "2")); } // crasches
void A::insert() { m.insert(make_pair("1", "2")); } // ok
If try to use the map inside the constructor I get Access violation reading location.
But if I use it after A has been initialized it works.Is this behavior correct?
What is the scope of the A object whose constructor invocation is causing the crash?
There are no guarantees as to the order that static initializers are executed, so that if your A object is also a global or static (as m is), it's quite possible that m does not exist yet in terms of being a validly constructed object, which would mean that your call to std::unordered_map::insert() would be invoked on uninitialized memory, thus leading to your crash.
A solution is to make sure that all of your A instances that depend on m are constructed explicitly by you and not statically/globally (or as the commenter added, if they are in the same TU, to order them properly), or to change the structure of A such that you can call a function on an instance later in order to do the insert. Whether or not this is a valid solution depends more on the overarching usage of A.
You are probably creating a class of type A in a static context somewhere in your application, ie before your main() function is executed, and therefore before m has been initialized.

Destruction order of static objects in C++

Can I control the order static objects are being destructed?
Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?
The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.
The other answers to this insist that it can't be done. And they're right, according to the spec -- but there is a trick that will let you do it.
Create only a single static variable, of a class or struct that contains all the other things you would normally make static variables, like so:
class StaticVariables {
public:
StaticVariables(): pvar1(new Var1Type), pvar2(new Var2Type) { };
~StaticVariables();
Var1Type *pvar1;
Var2Type *pvar2;
};
static StaticVariables svars;
You can create the variables in whatever order you need to, and more importantly, destroy them in whatever order you need to, in the constructor and destructor for StaticVariables. To make this completely transparent, you can create static references to the variables too, like so:
static Var1Type &var1(*svars.var1);
VoilĂ  -- total control. :-) That said, this is extra work, and generally unnecessary. But when it is necessary, it's very useful to know about it.
Static objects are destroyed in the reverse of the order in which they're constructed (e.g. the first-constructed object is destroyed last), and you can control the sequence in which static objects are constructed, by using the technique described in Item 47, "Ensure that global objects are initialized before they're used" in Meyers' book Effective C++.
For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static onject?
Ensure that it's constructed before the other static object.
How can I control the construction order? not all of the statics are in the same dll.
I'll ignore (for simplicity) the fact that they're not in the same DLL.
My paraphrase of Meyers' item 47 (which is 4 pages long) is as follows. Assuming that you global is defined in a header file like this ...
//GlobalA.h
extern GlobalA globalA; //declare a global
... add some code to that include file like this ...
//GlobalA.h
extern GlobalA globalA; //declare a global
class InitA
{
static int refCount;
public:
InitA();
~InitA();
};
static InitA initA;
The effect of this will be that any file which includes GlobalA.h (for example, your GlobalB.cpp source file which defines your second global variable) will define a static instance of the InitA class, which will be constructed before anything else in that source file (e.g. before your second global variable).
This InitA class has a static reference counter. When the first InitA instance is constructed, which is now guaranteed to be before your GlobalB instance is constructed, the InitA constructor can do whatever it has to do to ensure that the globalA instance is initialized.
Short answer: In general, no.
Slightly longer answer: For global static objects in a single translation-unit the initialization order is top to bottom, the destruction order is exactly reverse. The order between several translation-units is undefined.
If you really need a specific order, you need to make this up yourself.
Theres no way to do it in standard C++ but if you have a good working knowledge of your specific compiler internals it can probably be achieved.
In Visual C++ the pointers to the static init functions are located in the .CRT$XI segment (for C type static init) or .CRT$XC segment (for C++ type static init) The linker collects all declarations and merges them alphabetically. You can control the order in which static initialization occurs by declaring your objects in the proper segment using
#pragma init_seg
for example, if you want file A's objects to be created before file B's:
File A.cpp:
#pragma init_seg(".CRT$XCB")
class A{}A;
File B.cpp:
#pragma init_seg(".CRT$XCC")
class B{}B;
.CRT$XCB gets merged in before .CRT$XCC. When the CRT iterates through the static init function pointers it will encounter file A before file B.
In Watcom the segment is XI and variations on #pragma initialize can control construction:
#pragma initialize before library
#pragma initialize after library
#pragma initialize before user
...see documentation for more
Read:
SO Initialization Order
SO Solving the Order of Initialization Problem
No, you can't. You should never rely on the other of construction/destruction of static objects.
You can always use a singleton to control the order of construction/destruction of your global resources.
Do you really need the variable to be initialized before main?
If you don't you can use a simple idiom to actually control the order of construction and destruction with ease, see here:
#include <cassert>
class single {
static single* instance;
public:
static single& get_instance() {
assert(instance != 0);
return *instance;
}
single()
// : normal constructor here
{
assert(instance == 0);
instance = this;
}
~single() {
// normal destructor here
instance = 0;
}
};
single* single::instance = 0;
int real_main(int argc, char** argv) {
//real program here...
//everywhere you need
single::get_instance();
return 0;
}
int main(int argc, char** argv) {
single a;
// other classes made with the same pattern
// since they are auto variables the order of construction
// and destruction is well defined.
return real_main(argc, argv);
}
It does not STOP you to actually try to create a second instance of the class, but if you do the assertion will fail. In my experience it works fine.
You can effectively achieve similar functionality by having a static std::optional<T> instead of a T. Just initialize it as you'd do with a variable, use with indirection and destroy it by assigning std::nullopt (or, for boost, boost::none).
It's different from having a pointer in that it has preallocated memory, which is I guess what you want. Therefore, if you destroy it & (perhaps much later) recreate it, your object will have the same address (which you can keep) and you don't pay the cost of dynamic allocation/deallocation at that time.
Use boost::optional<T> if you don't have std:: / std::experimental::.