Memory alocated for Creating object inside a function? - c++

As objects are created from same class. Each object contains the variable defined in the class except those which are defined in the methods of that class. Variable in functions of the same object are shared memory right? If we have a function where we create an object of the same class, where will be the reference reside? Isnt that reference be shared too?

Methods are no different from any other function with regard to memory use: local variables are created when execution reaches their declaration, and (unless static) they are destroyed, and their memory reclaimed, when execution leaves the block it. (This happens, at latest, when the function returns.) There is no connection to the this object or any of its members. Nor does the variable having the same type as the method’s class make any difference.
In some sense, that does make the memory “shared”: it will be rapidly reclaimed and (typically) reused. But that’s nothing special, and don’t think that it means more than it does: if a method is recursive, or invoked concurrently by more than one thread, each copy has its own locals—again, just like any other function.
Finally, any function or method can allocate memory dynamically; the lifetime and sharing of the allocated object may be unrelated to that of the variable used to refer to it.

Related

Thread model and class instance memory management

Assume we created an instance of a class in the stack. I understand that the compiler gives it a specific amount of memory depending on the types and amount of fields in that instance. But I am confused about the instance methods. I assume they have their own stack frame.
What I don't understand:
Where the stack frame of the instance method is located? Are they located inside of the instance stack frame or they are stored elsewhere?
Is there only one instance method stack frame created for many instances of the class
if so, then what if two objects of the same class at the same time will call the same function from different threads?
Like normal functions, there are multiple pieces of memory associated with member functions in C++. First, there's the actual assembly instructions that make up the member function, which is usually put into the code segment and shouldn't be of any concern. Second, every time that member function is invoked, additional stack space is reserved for all of the local variables ("automatic objects") inside of that call, which is cleaned up when the call returns. I should specifically point out that functions don't have some fixed preallocated memory for their stack space - if a function is recursive, for example, you might have multiple stack frames active for that function at the same time. Rather, there's as many stack frames as needed.
When you declare a local variable of class type in C++, you only get the memory for the object itself. No extra memory is allocated to hold the member functions of that object - as mentioned above, the member function memory is either placed away in the data segment or is allocated as needed when you call the member functions. Specifically, if you call a member function on the object you've declared, then the program will allocate a new stack frame for that member function, call the function, and clean up the memory when the function returns. There is no extra "premium" paid for having member functions; they don't actually influence the size of the object (though having one or more virtual functions in your class may add a one-time cost to the size of your object).
Of course, this is all implementation-dependent; an implementation in principle could allocate extra space to store the member functions inside the object, but to the best of my knowledge no standard C++ implementations will do this. (If you know what a vtable is, the object might have a vtable pointer, but not all the vtable entries).
Hope this helps!
1. Where the stack frame of the instance method is located? Are they located inside of the instance stack frame or they are stored elsewhere?
There's no such thing like an instance stack frame. Stack frames are created in the actual execution thread's call stack.
2. Is there only one instance method stack frame created for many instances of the class
See my answer for 1.. There are different call stacks per thread, yes.
3. if so, then what if two objects of the same class at the same time will call the same function from different threads?
As said before, there are different stack frames created for each thread. There aren't any call stack frames per instance. It's only the different implicitly passed this pointers, that distinguish the instances accessed.
A method is essentially a "chunk" of opcodes (machine operations), located in the (read-only) code-section of the executable image.
So methods have nothing to do with the stack (in terms of the memory in which they reside).
Nevertheless, they do access the stack whenever they perform operations on local variables.
An instance of a class does not "contain" the class methods, but only the class attributes (the variables that you define in the class), and possibly a pointer to the V-Table of the class (if you define one or more virtual functions in the class or in one of its base-classes).
As long as a method operates on non-static local variables or non-static member variables, it is thread-safe, as these variables are allocated in the stack every time the method is invoked, and every thread has its own stack (its own separate area within the entire stack, to be more accurate).
Once a method operates on variables that are not allocated in the stack (static local variables, static member variables, static global variables or non-static global variables), it becomes thread-unsafe and has to be treated as such (typically with appropriate OS resources, such as semaphores, mutexes, etc).
Also, keep in mind that an inline function/method call may not create a stack frame at all.
And the che compiler may inline a funcition call for optimization.

Global Static Dynamically allocated objects C++

I have very specific question about dynamically allocated static global object. In my project i have few object which I need to access from various places across the threads throughout the application lifetime. I want to create the at the application initialization and distroy when application exits. So I tried following,
Header File: MyObjectFactory.h
class MyObjectFactory{
public:
static MyObject* GetMyObject();
};
Source File: MyObjectFactory.cpp
static MyObject* gMyObject = 0;
MyObject* MyObjectFactory::GetMyObject(){
if(gMyObject == 0)
{
gMyObject = new MyObject();
}
return gMyObject;
}
This code seems like working but i want to clear few things.
Object will be created only once and then reference to object will be returned.
( I want this because MyObject encapsulate few system resource like text file)
MyObject gets destroyed when Application exits.
Where would be object created Heap (as I am using new ) or global memory (as I am using static)? Or am I violating any OOP principle?
Is it ok to call MyObjectFactory::GetMyObject() from multiple thread?
Is this a good way to achieve somewhat similar to Singleton?
Please let me know your input.
Thank You so much!
The standard way to achieve both proper destruction and correct initialization with minimal headache uses block-local statics, like this:
foo.hpp:
struct Foo
{
static Foo & get();
// ...
};
foo.cpp:
#include "foo.hpp"
Foo & Foo::get()
{
static Foo impl;
return impl;
}
Now you can say Foo::get() anywhere in your code. No pointers, no dynamic allocations, and nothing gets leaked. A truly static singleton.
Object will be created only once and then reference to object will be returned. ( I want this because MyObject encapsulate few system resource like text file)
MyObject* is a pointer type, not a reference type. gMyObject is a variable of type pointer to MyObject.
MyObject gets destroyed when Application exits.
It does not, noone calls delete on your pointer so you have a leak.
Where would be object created Heap (as I am using new ) or global memory (as I am using static)? Or am I violating any OOP principle?
If you are using new, the object is created at the 'heap'. The static only applies to the pointer to your object, not the object itself.
Is it ok to call MyObjectFactory::GetMyObject() from multiple thread?
It's not, you can cause multiple initializations if you have concurrent threads and the object wasn't constructed yet.
Is this a good way to achieve somewhat similar to Singleton?
It's not. Or maybe it is, but a singleton is usually a bad way to achieve something (and I only said usually).
Object will be created only once and then reference to object will be returned.
If your program is single-threaded, yes (although in your example it returns a pointer not a reference). Otherwise there is a danger of two threads creating separate copies of the object; or in fact of anything else happening, since the behaviour is undefined in that case.
MyObject gets destroyed when Application exits.
No, objects created with new will only be destroyed by delete, never automatically, so this object is leaked. Whether or not that is a problem depends on whether all the resources it uses are automatically reclaimed by the system.
Where would be object created Heap (as I am using new ) or global memory (as I am using static)?
The object is allocated from the free store (aka heap); the pointer to it is static.
Is it ok to call MyObjectFactory::GetMyObject() from multiple thread?
Only if you can ensure that the object has already been created before either of them call it.
Is this a good way to achieve somewhat similar to Singleton?
There's no good way to achieve that in C++. The best approach is to avoid globally accessible objects altogether; create it somewhere, and pass references to whatever needs it.
If you really want a global object, then there are a few options, each with their own deathtraps:
A simple global object. Be careful of the Initialisation Order Fiasco if you have more than one of these, with dependencies between them.
A function containing a static object, returning a reference to this. That is guaranteed to be initialised when you use it, and is thread-safe on a C++11 compliant implementation (and on many earlier implementations too). However, during program shutdown there is a danger that it might be destroyed before other static objects that are still trying to access it - you could perhaps avoid that by dynamically allocating and leaking the object, as in your approach. There may also be some runtime overhead from ensuring thread-safe construction.
A lazily-allocated dynamic object (like you have), as long as you either make sure it's initialised before launching multiple threads, or add thread safety (which isn't entirely straightforward, and will add run-time overhead).

C++ method variable declaration

Currently I'm looking into this C++ source code. I'm not a C++ dev.
void SomeClass::SomeMethod() const
{
vector<Thing> things(count);
...
//Elements are added or replaced in things but no deallocation of things here
}
SomeMethod is called a lot of times. Could anyone confirm that there is no leak and things is allocated only once, reference would be appreciated.
The vector is created everytime you enter the function and destroyed (destroying all objects and freeing all the memory) when it leaves scope (when the function ends). There's no leak, but there's a lot of allocations and deallocations if you call that function frequently.
You have 2 solutions to avoid that:
(preferred) Make this vector a class field (with attribute mutable in order to allow it to be changed by a const method),
Make this vector a static variable.
"things" is a local auto variable.
Another post has a answer for this: Where are the local, global, static, auto, register, extern, const, volatile variables are stored?
Provided Thing is correctly implemented insofar as its destructor and other member functions (especially copy constructor because that's used in vector housekeeping) correctly handle all memory for its data members, what this will do is create a new vector<Thing> on each call to the function.
The resulting local variable things gets correctly freed, including destruction of every Thing member, when the variable goes out of scope (i.e. on function exit).
It's impossible to be more definitive without seeing all the code in the method and in Thing, but this usage is on the face of it correct.
That lays localy in that function. When it goes out of scope, it will delokate the memory by itself; all of the STL containers do.

Question about pointers and objects?

Just wondering, if I statically create an object that has a pointer as a data member and then the object goes out of scope, what happens to the pointer?
Chuma
Nothing happens to the pointer at all, it just ceases to exist. If it was pointing to something that needed to be freed, you just got a memory leak.
Either add code to the destructor that does the proper cleanup of the pointer, or use "smart pointers" that clean up after themselves automatically.
Edit: If you actually meant you were creating a static object, by declaring it with the static keyword inside a function, then the answer is different. A static object, once constructed by the first execution of the function that declares it, continues to live until the program ends. Its data members, including pointers, will remain valid. Subsequent calls to the function will access the same object. If the object has allocated any memory, it will remain allocated unless something explicitly deletes it.
The pointer gets destroyed with the rest of your object. Whatever it was pointing at isn't affected at all (unless the object's destructor does something with it).
Revised answer
There are two properties of a variable which are relevant here - scope and lifetime - and I think the question is conflating the two.
In all the contexts I can think of, a statically allocated object has a lifetime that is essentially the lifetime of the process. There are some technical details about exactly when the object is first initialized (constructed), but the net result is essentially the same - a statically allocated object exists for the duration of the process.
However, an object may come into scope, and go out of scope, as the thread of control moves between functions in the program. The scope of the object is where it is visible by name. It may be accessible elsewhere if a pointer to it (or reference to it) is passed to other functions where it would not otherwise be in scope.
Since a statically allocated object has a lifetime of the duration of the program, pointer members of that object do not change because the object goes out of scope; the object continues to exist unchanged, and the pointer members continue to point to the same place. Clearly, if a pointer in the statically allocated object points to a variable that had automatic duration and that pointed-to variable ceases to exist because it is destroyed, then the pointer in the statically allocated object points to an invalid location.
However, the key point is that the statically allocated object is not changed, and the pointer members are not changed, but changes in scope. And there are no leaks caused by the changes in scope.
Original answer
In all the contexts I can think of, a statically allocated object can't go out of scope, pretty much by definition. I suppose that if a shared library was loaded and then unloaded, then a statically allocated object might go 'out of scope', but otherwise...
If this premise is correct, then the second half of the question is easy. You can take either of two views:
Since the static object never goes out of scope, nothing happens to the static object and its pointer member, and it will be pointing to the same place when the object comes back into scope - where scope here means 'into a function that could access the static object'.
When the thread of control leaves a scope that could access the static object, nothing happens to the static object and its pointer member, and it will be pointing to the same place when the object next comes back into scope.
Which is basically saying the same thing, twice. If I said it a third time, it would automatically be true, wouldn't it? So, a statically allocated object doesn't go out of scope (even if it is not always accessible from the current function) and so nothing happens to the pointer members. There...what I said is so. I think!
What am I missing? Does 'statically created object' have a meaning I've not thought of?

C++: Do static primitives become invalid at program exit?

Assume I have a function like this:
MyClass &MyFunction(void)
{
static MyClass *ptr = 0;
if (ptr == 0)
ptr = new MyClass;
return MyClass;
}
The question is at program exit time, will the ptr variable ever become invalid (i.e. the contents of that ptr are cleaned up by the exiting process)? I realize that this function leaks, but it is only an example for simplicity.
The same question also applies to other primitives besides pointers as well. How about if I have a static integer, does the value of that integer always persist throughout exit or is variable due to static destruction order issues?
EDIT:
Just to clarify, I want to know what actually happens to the contents of the static pointer (or any other primitive type like an int or a float) and not to the memory it is pointing to. For instance, imagine that the ptr points to some memory address which I want to check in the destructor of some other static class. Can I rely on the fact that the contents of the ptr won't be changed (i.e. that the pointer value won't be cleaned up during the static destruction process)?
Thanks,
Joe
When you process exits the all memory pages allocated to it will be freed by the OS (modulo shared memory pages that someone else may be using).
However, as others point out the destructor for MyClass is never called. Nor is the value pointed to by ptr ever changed. If you have a static int with the value 123 then its value will stay 123 through to the very end of the process' lifetime.
In modern operating systems, all of an application's memory is allocated on a "heap" specific to that application. When the application exits, all of the memory in that heap will be freed.
So, the memory will be deallocated, but: the destructor for MyClass will never be called. This can be an issue if the destructor is responsible for releasing any non-memory resources (file system locks are a common example).
To answer your question:
'imagine that the ptr points to some memory address which I want to check in the destructor of some other static class'
The answer is yes.
You can see the value of the pointer (the address).
You can look at the content if you have not called delete on the pointer.
Static function variables behave in the same way as static class variables and global variables (aka non local static), in that there destructors will be called in reverse order of creation. Integers, floats and pointers (POD) do not have destructors so nothing happens to them until the processes is removed.
POD objects: Data can safely by referenced from the destructor of other objects (even global s).
Other static objects (i.e. those with destructors): In the general case, it is not safe to accesses these objects after main() has exited because the order of destruction is not know (it is the reverse of the order of creation, but the order of creation is complex see: Construction Order ). It can be done but you have to take explicit precautions to make sure the object is still alive.
Note: non local static:
The memory will always be there, the object will just not be valid after a destructor is called (note POD does not have a destructor).
Note: Stack:
Only valid until the scope in which they are declared is left.
After the stack is popped the memory page that it is on could potentially be dropped resulting in SEG faults if you attempt to access it.
Note: Heap:
Valid until you call delete on the pointer that allocated it.
Once a pointer is delete the value is potentially random as it may be re-used.
Potentially the page the memory was on can also be dropped. Any access to a dropped page would result in a SEG fault.
To answer your updated question, I would say yes: you can rely on the value of that static pointer remaining throughout the static destruction process. The memory it points to may have been freed, but the value of the pointer itself should remain unchanged, unless the destructor of another static class makes a change to it.
The short answer is "no": your pointer will not "become invalid" at program exit time. I.e. the pointer value will not automatically be reset to null, and destructor of the MyClass object to which it points will not automatically be called.
This is because a pointer is a "primitive type", i.e. not an object.
If you have a non-local (i.e. global or static) variable which is an object, then the rules are different: the destructor of the object will be called when the program terminates by calling exit() or by returning from the main function. It will not be called if the program terminates by calling abort().