Global Static Dynamically allocated objects C++ - 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).

Related

Create shared_ptr to stack object

In my method a Player object is created like:
Player player(fullName,age);
My teacher gave us a piece of code with a constructor that takes a shared_ptr to a player object.
//constructor of the class
SomeClass(const std::shared_ptr<Socket> client, std::shared_ptr<Player> player)
Lets say we want to call the constructor of SomeClass and pass the player object we created on stack.
Is it ever safe/possible/good to create a shared_ptr from a stack object?
To make the question more understandable lets say we have two big code projects and we want to merge them so a method from one project is called from another one, should we rewrite all the files to use shared_ptr or stack objects exclusivly (for the methods that needs to be connected) or should we just create a shared_ptr to the stack object.
Why im not sure of the result:
What if the scope where the stackobject is created ends but the shared_ptr is still used and vise versa.
The stackobject gets deleted when out of scope or does it stay alive because there is still a reference to the object (in another class though)?
The shared_ptr goes out of scope and tries to delete the object, can it even though the stackobject is refering to it?
Note: I know I could just use the following and pass player
shared_ptr<Player> player{ new Player {fullName,age} };
Is it ever safe/possible/good to create a smart_ptr from a stack object?
Safe? Only if you can guarantee that the stack which created that object will only be ended after all shared_ptr's that pseudo-own it.
Possible? Sure: pass shared_ptr's constructor a deleter object that does nothing:
auto sptr = shared_ptr<Player>(&player, [](Player *) {});
When the last shared_ptr is destroyed, the deleter will be called and nothing will be deleted.
Good? Not really. As noted above, safety is not something that can be universally guaranteed in such code. Depending on your code structure, this may be legitimate. But it requires great care.
This SomeClass is expecting to claim ownership of a resource; that's why it's taking a shared_ptr. You're kind of lying to it by passing it a shared_ptr that doesn't really own the object it references. That means the onus is on you and your code structure to not violate the promise you made to SomeClass that it would have shared control over that object's lifetime.
The purpose of a shared pointer is to manage the lifetimes of dynamically created objects. As long as there is any shared pointer that points at an object, that object must still exist; when the last shared pointer that points at an object is destroyed, that object gets destroyed.
Stack objects have a fundamentally different lifetime: they exist until the code exits from the scope in which they were created, and then they are destroyed.
The two notions of lifetime are incompatible: there is no way a shared pointer can ensure that a stack object that has gone out of scope still exists.
So don't mix the two.
Is it ever safe/possible/good to create a shared_ptr from a stack object?
I agree with #Nicolas Bolas that it is not safe. But it may be safe to create a shared_ptr from a copy of a stack object
shared_ptr<Player> playerPtr(new Player(player));
if Player is copy-able of course.
It's not safe to create a shared pointer to a stack object, because the stack object is due for destruction as soon as its containing function returns. Local objects are allocated and deallocated implicitly and automatically and trying to intervene is surely invoking many kinds of undefined behavior.
Use move semantics to create the shared_ptr
std::shared_ptr<Player> player_shared_ptr{ std::make_shared(std::move(player)) };
In this way, a copy is avoided. You may need to implement move constructor though on relevant classes for this approach to work. Most/all std objects support move semantics out of the box (eg. string, vector, etc.)
Safe is a strong word.
However, You can make the code safer by defining a StackObjectSharedPtr, forcing the shared_ptr instanciated type to include a "special" StackObjectDeleter
using PlayerStackSP = std::shared_ptr <Player, StackObjectDeleter> ;
class StackObjectDeleter {
public:
void operator () (void*) const {}
};
Player player(fullName,age);
std::shared_ptr<PlayerStackSP, StackObjectDeleter> player(&player, StackObjectDeleter());
The StackObjectDeleter replaces the default_delete as the deleter object. default_delete simply calls delete (or delete []). In case of StackObjectDeleter, nothing will happen.
This is a step further of #Nicol Bolas's answer.

Usage of member variable referencing own instance

I am currently investigating code of a C++ library which is not written by me.
The code seems to be a little bit ugly to me, but I have to admin that I am no C++ pro.
The Library has a class, lets call it ExampleClass, which has a member variable std::shared_ptr<ExampleClass> this_ec which is not set in the constructor, but seems to be set always when another object creates an instance of ExampleClass:
std::shared_ptr<ExampleClass> ec = std::make_shared<ExampleClass>(...);
ec->this_ec = ec;
Could it be that this is used to prevent garbage collection?
Could it be that this is used to prevent garbage collection?
Yes, if by "garbage collection", you mean "automatic deletion". The object won't be deleted as long as at least one shared pointer exists, so this will keep the object alive at least until that pointer is reset or reassigned.
This rather defeats the purpose of using smart pointers, since it's now easy to leak objects by losing all external pointers to them. Tread carefully here.
A less error-prone way to make a shared pointer to the current object available within the class is to inherit from enable_shared_from_this<ExampleClass>, and obtain the pointer with shared_from_this(). This effectively stores a weak pointer, which doesn't prevent deletion.

when to use new in C++?

What's a good policy for when to use "new" to make an instance of a class? I've been hobby programming C++ for a while but I'm still not for sure when is the best time to do this:
MyClass thing(param1, param2);
over this:
MyClass* thing;
thing = new MyClass(param1, param2);
Any advice?
Design-wise, use automatic (stack) allocation as much as possible. Whenever you need to extend the lifetime of an object beyond a certain scope, then dynamically allocate it.
And even so, never dynamically allocate things raw. Always keep them wrapped into some sort of wrapper that implements Scope-Bound Resource Management (SBRM, first known under the dumb/awkward name Resource-Acquisition Is Initialization or RAII.) That is, dynamic allocations should be kept in automatic objects that will clean up automatically!
A good example of this is std::vector: you cannot leak the memory internal to a vector, because it's destructor is run in every scenario when memory should be free'd, and it will free it for you. auto_ptr is the first and only smart pointer available in the standard library, but it's pretty bad. Better is to use shared_ptr, or many of the other popular smart pointers available in Boost and/or TR1 and/or C++0x.
Performance-wise, objects allocated on the stack can be done so very quickly (the stack size is increased per-function-call, so all the required memory has been allocated up-front by a simple move of a pointer.) Contrarily, dynamic allocation generally requires much more time. It's quite possible to get speedy dynamic allocations with custom allocation schemes, but even the best will still be slower than stack allocation.
Occasionally, you might find you spend too much time copying objects around. In this case, it may be worth it to dynamically allocate it and merely move pointers around. However, please note I said "find". This kind of change is something you find by profiling and measuring, never guessing.
So: Automatic allocation when possible, dynamic allocation when needed.
The first approach creates a local instance on the stack that goes away when the calling function exits. The second creates an instance that stays on the heap until (and if) you explicitly release it again. The choice depends on what kind of control and lifetime you want for your object.
The rule of thumb is: if it works without new, don't use new.
In general: you don't need to use new if you plan to delete the object in the same scope. If the object is quite large, you may want to use new.
You may want to look into the difference between heap and stack memory if you want to know the details.
First, ask yourself the question, does it make sense for the object to be copied when another function wants it?
If it makes sense to copy the object, your best bet is to create everything on the stack or as member variables and then just pass copies around when needed.
If it does not make sense to copy the object, you'll need to use new form so that you can safely pass the pointer to the object. You have to use a pointer (or reference) because as noted it does not make sense to copy the object.
There are two exceptions I'm aware of:
If you know the object isn't going to be used after the current function is finished, you can create the object on the stack so that it is deleted. Just make very sure nobody holds on to a pointer to it afterwards! (I rarely find this is the case, but it happens)
If the object is used internally by another class which itself shouldn't be copied around, you can just put it in as a member variable. Since the object it is in won't be copied, and its only for internal use that will be safe.
MyClass thing(param1, param2); //memory for thing is allocated on the process stack(static allocation)
MyClass* thing;
thing = new MyClass(param1, param2); //memory is allocated dynamically on the heap(free store) for thing
The difference lies here:
int main()
{
{
MyClass thing(param1, param2); //thing is local to the scope
} //destructor called for thing
//cannot access thing (thing doesn't exist)
}
int main()
{
{
MyClass* thing;
thing = new MyClass(param1, param2);
}
//the object pointed to by thing still exists
//Memory leak
}
For large objects you must allocate memory dynamically(use new) because the process stack has a limited size.

Pointer allocation vs normal declaration

sometimes I see in various C++ programs, objects declared and used like so:
object *obj = new object;
obj->action();
obj->moreAction();
//etc...
Is there any benefit of doing that, instead of simply doing:
object obj;
obj.action();
obj.moreAction();
//etc
Yes - you can store the pointer in a container or return it from the function and the object will not get destroyed when the pointer goes out of scope. Pointers are used
to avoid unnecessary copying of object,
to facilitate optional object creation,
for custom object lifetime management,
for creating complex graph-like structures,
for the combinations of the above.
This doesn't come for free - you need to destroy the object manually (delete) when you no longer need it and deciding when this moment comes is not always easy, plus you might just forget to code it.
The first form, allocating objects on the heap, gives you full control of (and full responsibility for) the object's live time: you have to delete obj explicitly.
In the second form, the object is automatically and irrevocably destroyed when obj goes out of score (when leaving the current code block).
One other reason no-one has mentioned.
The stack is typically 1Mb, so creating large objects must be done on the heap ( with new)
Basically, you should only use "new" if you want an object to live beyond the lifetime of the scope you create it in. For eg:
X* g(int i) { /* ... */ return new X(i); } // the X outlives the call of g()
If you want an object to live in a scope only, don't use "new" but simply define a variable:
{
ClassName x;
// use x
}
It comes down to having more control over the lifecycle of the object in question (when using new).
Yes there is a good reason: you have much more chance to have a correct program when using the latter form..
The problem is that the former form (pointer) is a Cism, in C++ you should use a smart pointer to ensure proper destruction of the object at the end of its life.
Now, if you use std::auto_ptr<Object> obj(new Object()); you have 3 benefits:
you now manage the life cycle of your object explicitly (but cannot forget it)
you can store you object into a container with polymorphism
you do not clog the stack, and thus have less risk of running into a stack overflow
one can ask in a opposite way: when should you use strange first option? basically if you want to allocate big object, because if you don't have to do it and you can put it on the stack it will be much faster option: this is one of main advantages of using C++ over JAVA, which puts all objects on the heap. and this benefit is specially true when dealing with many, many allocations of little objects: put them on stack to increase speed. there is cost overhead of dereferencing pointer. you can find here info about boost pool library which provides us with tools to manage such allocations.

c++: when to use pointers?

After reading some tutorials I came to the conclusion that one should always use pointers for objects. But I have also seen a few exceptions while reading some QT tutorials (http://zetcode.com/gui/qt4/painting/) where QPaint object is created on the stack. So now I am confused. When should I use pointers?
If you don't know when you should use pointers just don't use them.
It will become apparent when you need to use them, every situation is different. It is not easy to sum up concisely when they should be used. Do not get into the habit of 'always using pointers for objects', that is certainly bad advice.
Main reasons for using pointers:
control object lifetime;
can't use references (e.g. you want to store something non-copyable in vector);
you should pass pointer to some third party function;
maybe some optimization reasons, but I'm not sure.
It's not clear to me if your question is ptr-to-obj vs stack-based-obj or ptr-to-obj vs reference-to-obj. There are also uses that don't fall into either category.
Regarding vs stack, that seems to already be covered above. Several reasons, most obvious is lifetime of object.
Regarding vs references, always strive to use references, but there are things you can do only with ptrs, for example (there are many uses):
walking through elements in an array (e.g., marching over a standard array[])
when a called function allocates something & returns it via a ptr
Most importantly, pointers (and references, as opposed to automatic/stack-based & static objects) support polymorphism. A pointer to a base class may actually point to a derived class. This is fundamental to the OO behavior supported in C++.
First off, the question is wrong: the dilemma is not between pointers and stack, but between heap and stack. You can have an object on the stack and pass the pointer to that object. I assume what you are really asking is whether you should declare a pointer to class or an instance of class.
The answer is that it depends on what you want to do with the object. If the object has to exist after the control leaves the function, then you have to use a pointer and create the object on heap. You will do this, for example, when your function has to return the pointer to the created object or add the object to a list that was created before calling your function.
On the other hand, if the objects is local to the function, then it is better to use it on stack. This enables the compiler to call the destructor when the control leaves the function.
Which tutorials would those be? Actually, the rule is that you should use pointers only when you absolutely have to, which is quite rarely. You need to read a good book on C++, like Accelerated C++ by Koenig & Moo.
Edit: To clarify a bit - two instances where you would not use a pointer (string is being used here as an exemplar - same would go for any other type):
class Person {
public:
string name; // NOT string * name;
...
};
void f() {
string value; // NOT string * value
// use vvalue
}
You usually have to use pointers in the following scenarios:
You need a collection of objects that belong to different classes (in most cases they will have a common base).
You need a stack-allocated collection of objects so large that it'll likely cause stack overflow.
You need a data structure that can rearrange objects quickly - like a linked list, tree ar similar.
You need some complex logic of lifetime management for your object.
You need a data structure that allows for direct navigation from object to object - like a linked list, tree or any other graph.
In addition to points others make (esp. w.r.t. controlling the object lifetime), if you need to handle NULL objects, you should use pointers, not references. It's possible to create a NULL reference through typecasting, but it's generally a bad idea.
Generally use pointers / references to objects when:
passing them to other methods
creating a large array (I'm not sure what the normal stack size is)
Use the stack when:
You are creating an object that lives and dies within the method
The object is the size of a CPU register or smaller
I actually use pointers in this situation:
class Foo
{
Bar* bar;
Foo(Bar& bar) : bar(&bar) { }
Bar& Bar() const { return *bar; }
};
Before that, I used reference members, initialized from the constructor, but the compiler has a problem creating copy constructors, assignment operators, and the lot.
Dave
using pointers is connected with two orthogonal things:
Dynamic allocation. In general, you should allocate dynamically, when the object is intended to live longer that the scope in which it's created. Such an object is a resource which owner have to be clearly specified (most commonly some sort of smart pointer).
Accessing by address (regardless of how the object was created). In this context pointer doesn't mean ownership. Such accessing could be needed when:
some already existing interface requires that.
association which could be null should be modeled.
copying of large objects should be avoided or copying is impossible at all, but the reference can't be used (e.g., stl collections).
The #1 and #2 can occur in different configurations, for example you can imagine dynamically allocated object accessed by pointer, but such the object could also by passed by reference to some function. You also can get pointer to some object which is created on the stack, etc.
Pass by value with well behaved copyable objects is the way to go for a large amount of your code.
If speed really matters, use pass by reference where you can, and finally use pointers.
If possible never use pointers. Rely on pass by reference or if you are going to return a structure or class, assume that your compiler has return value optimization. (You have to avoid conditional construction of the returned class however).
There is a reason why Java doesn't have pointers. C++ doesn't need them either. If you avoid their use you will get the added benefit of automatic object destruction when the object leaves scope. Otherwise your code will be generating memory errors of various types. Memory leaks can be very tricky to find and often occur in C++ due to unhandled exceptions.
If you must use pointers, consider some of the smart pointer classes like auto_ptr. Auto destruction of objects is more than just releasing the underlying memory. There is a concept called RAII. Some objects require additionally handing on destruction. e.g. mutexes and closing files etc.
Use pointers when you don't want your object to be destroyed when the stack frame is emptied.
Use references for passing parameters where possible.
Speaking about C++, objects created on the stack cannot be used when the program has left the scope it was created in. So generally, when you know you don't need a variable past a function or past a close brace, you can create it on the stack.
Speaking about Qt specifically, Qt helps the programmer by handling a lot of the memory management of heap objects. For objects that are derived from QObject (almost all classes prefixed by "Q" are), constructors take an optional parameter parent. The parent then owns the object, and when the parent is deleted, all owned objects are deleted as well. In essence, the responsibility of the children's destruction is passed to the parent object. When using this mechanism, child QObjects must be created on the heap.
In short, in Qt you can easily create objects on the heap, and as long as you set a proper parent, you'll only have to worry about destroying the parent. In general C++, however, you'll need to remember to destroy heap objects, or use smart pointers.