I want to know if thread1, calls a class function via passed object 'obj->fun()' and that object is deleted in the background by some other thread say thread2 what happens to function execution by thread1.
Example:
ClassA {
int functionA() {
...condition(started_execution);
int a=0;
a++;
printf(....a);
return a;
}
};
void startExecution(void *arg) {
/*casting code object A*/
A->functionA();
}
int main() {
ClassA *A = new ClassA();
pthread_create(....,startExecution,(void *)A);
....wait_for(started_execution);
delete A;//just want to know the behaviour and not join method.
}
Question: In the above scenario, A->functionA calls function functionA. If the function is executing, what will the impact of delete A on function execution since object A invoked it? functionA is not working on shared data?
If the function is executing, what will the impact of delete A on function execution since object A invoked it?
If the executing function uses this in any way, the impact would be undefined behaviour. By using this I mean access any data member or base sub object, call any member function, indirecting this or passing this to some function that would do any of those things.
Your functionA doesn't appear to use this in any way after setting the condition variable, so there would be no impact whatsoever - assuming the condition variable access itself is properly synchronised.
However, it's not a very good idea to do this, since it is not visible in the definition of functionA that no member must be accessed. It would be easy for a programmer to not follow that requirement when changing the function later.
As far as I can tell, this situation is analogous to the case of delete this; which is considered to conform to standard, but is potentially dangerous: Is delete this allowed?
Related
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.
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.
Program crushing,when i trying to change class variable
for example:
class ITask
{
public:
ITask();
void perform(int,int);
private:
int total = 0;
}
__________implementation___________
void ITask::perform(int a,int b)
{
int time=rand()%10;
this->total=time;
}
Without string this->total=time; program works.
As you said, you use ITask* task; task->perform(a,b);. However, ITask* task; only declares a pointer to an ITask, it does not create an instance. So your perform member function tries to write to a memory location where it thinks total resides, but in fact the memory is not allocated for that purpose. Hence the crashing which depends on the presence of the line this->total=time;. Note however that the fact that it works without that line is purely implementation defined, as it is still undefined behavior to call a non-static member function without an instance, i.e. without a valid this pointer.
Either use
ITask task;
task.perform(a,b);
(to create an ITask local to the function) or
ITask* task = new ITask();
task->perform(a,b);
//later deallocate:
delete task;
(to create an ITask that lives until you call the delete). Both create actual objects.
I want to know what would happen when destructor gets called on an object when the object is stuck in an infinite while loop in a different thread.
// Main thread creates the object
MyClass _obj = new MyClass():
// doing some stuff
delete _obj;
Where,
MyClass::MyClass()
{
// Start a thread which calls MyClass::MyPollingFn()
}
MyClass:: MyPollingFn()
{
// runs in new child thread
while(true)
{
// doing some work
// sleep(5 seconds)
}
}
Explanation:
There is a class object of MyClass which creates a thread and runs MyPollingFn method in an infinite loop. Every iteration of this method can change some class variables. Is it ok to destroy the object from parent thread which holds the object? Is there any possibility of this giving an issue?
If MyPollingFn ever touches this, explicitly or implicitly (e.g. by accessing non-static member variables), then this code would exhibit undefined behavior, as this would become a dangling pointer.
And if it doesn't touch this, then why make it a non-static member function?
There are several possible issues, including
1. Either you will try to join the thread in your destructor, in which case it will block.
Edit
i.e. if you add
MyClass::~MyClass()
{
myThread.join();
}
and leave the MyPollingFunction as it is, it will never finish, so the join will block.
End Edit
Though this code doesn't have a destructor, but perhaps it should.
2. Or the thread will try to "change some class variables" after the class has gone away.
Which is obviously bad.
It might be better to change the
while(true)
to
while(!finished)
where the finished is some kind of thread-safe flag (an e.g. atomic) and set it in the (currently non-existent) destructor.
I am trying to write a function that will check if an object exists:
bool UnloadingBay::isEmpty() {
bool isEmpty = true;
if(this->unloadingShip != NULL) {
isEmpty = false;
}
return isEmpty;
}
I am pretty new to C++ and not sure if my Java background is confusing something, but the compiler gives an error:
UnloadingBay.cpp:36: error: no match for ‘operator!=’ in ‘((UnloadingBay*)this)->UnloadingBay::unloadingShip != 0’
I can't seem to figure out why it doesn't work.
Here is the declaration for class UnloadingBay:
class UnloadingBay {
private:
Ship unloadingShip;
public:
UnloadingBay();
~UnloadingBay();
void unloadContainer(Container container);
void loadContainer(Container container);
void dockShip(Ship ship);
void undockShip(Ship ship);
bool isEmpty();
};
It sounds like you may need a primer on the concept of a "variable" in C++.
In C++ every variable's lifetime is tied to it's encompassing scope. The simplest example of this is a function's local variables:
void foo() // foo scope begins
{
UnloadingShip anUnloadingShip; // constructed with default constructor
// do stuff without fear!
anUnloadingShip.Unload();
} // // foo scope ends, anything associated with it guaranteed to go away
In the above code "anUnloadingShip" is default constructed when the function foo is entered (ie its scope is entered). No "new" required. When the encompassing scope goes away (in this case when foo exits), your user-defined destructor is automatically called to clean up the UnloadingShip. The associated memory is automatically cleaned up.
When the encompassing scope is a C++ class (that is to say a member variable):
class UnloadingBay
{
int foo;
UnloadingShip unloadingShip;
};
the lifetime is tied to the instances of the class, so when our function creates an "UnloadingBay"
void bar2()
{
UnloadingBay aBay; /*no new required, default constructor called,
which calls UnloadingShip's constructor for
it's member unloadingShip*/
// do stuff!
} /*destructor fires, which in turn trigger's member's destructors*/
the members of aBay are constructed and live as long as "aBay" lives.
This is all figured out at compile time. There is no run-time reference counting preventing destruction. No considerations are made for anything else that might refer to or point to that variable. The compiler analyzes the functions we wrote to determine the scope, and therefore lifetime, of the variables. The compiler sees where a variable's scope ends and anything needed to clean up that variable will get inserted at compile time.
"new", "NULL", (don't forget "delete") in C++ come into play with pointers. Pointers are a type of variable that holds a memory address of some object. Programmers use the value "NULL" to indicate that a pointer doesn't hold an address (ie it doesn't point to anything). If you aren't using pointers, you don't need to think about NULL.
Until you've mastered how variables in C++ go in and out of scope, avoid pointers. It's another topic entirely.
Good luck!
I'm assuming unloadingShip is an object and not a pointer so the value could never be NULL.
ie.
SomeClass unloadingShip
versus
SomeClass *unloadingShip
Well, you don't have to write so much code to check if a pointer is NULL or not. The method could be a lot simpler:
bool UnloadingBay::isEmpty() const {
return unloadingShip == NULL;
}
Plus, it should be marked as "const" because it does not modify the state of the object and can be called on constant instances as well.
In your case, "unloadingShip" is an object of class "UnloadingShip" which is not dynamically allocated (except when the whole class "UnloadingBay" is allocated dynamically). Thus, checking if it equals to NULL doesn't make sense because it is not a pointer.
For checking, if an object exists, you can consider going this way:
create a pointer to your object:
someClass *myObj = NULL // Make it null
and now where you pass this pointer, you can check:
if(!myObj) // if its set null, it wont pass this condition
myObj = new someClass();
and then in case you want to delete, you can do this:
if(myobj)
{
delete myObj;
myObj = NULL;
}
so in this way, you can have a good control on checking whether your object exists, before deleting it or before creating a new one.
Hope this helps!