How to re-use correctly a TMemoryStream in a cycle. For example I have a timer and I'm downloading something from internet directly in a TMemoryStream object.
this object is declared as global variable:
TMemoryStream *ms;
then I use it in a timer function:
ms = new TMemoryStream;
.... other operations with ms ....
then I use it in other function where i do not need this stream at the end and want to empty it, and i do:
delete ms;
and then again is called same timer function, and it does the same cycle allocating and deallocating. It is correctly by this way ?
or I should ms->Clear() or ms->Free() in my last function where stream is no more need ?
I'm interested in how to reuse same global variable to read the stream (allocate) and empty the stream (deallocate).
Generally it is not dangerous or a mistake to instantiate and free an object in a timer, because timer calls have no overlap while thread calls may have. As Remy said, it is better to use only Clear() in timer and at end delete stream inside OnDestroy or form destructor (__fastcall ~TForm1()).
Free() is Delphi's equivilent to C++'s delete - the object gets destroyed. If you just want to reuse the same object but empty out its contents each time, use Clear(). Just remember that at some point, you will need to call delete to free the object when you are not going to use it anymore.
Related
I am using boost 1.55 (io_service doc). I need to call the destructor on my io_service to reset it after power is cycled on my serial device to get new data. The problem is that when the destructor is called twice (re-trying connection), I get a segmentation fault.
In header file
boost::asio::io_service io_service_port_1;
In function that closes connection
io_service_port_1.stop();
io_service_port_1.reset();
io_service_port_1.~io_service(); // how to check for NULL?
// do I need to re-construct it?
The following does not work:
if (io_service_port_1)
if (io_service_port_1 == NULL)
Thank you.
If you need manual control over when the object is created and destroyed, you should be wrapping it in a std::unique_ptr object.
std::unique_ptr<boost::asio::io_service> service_ptr =
std::make_unique<boost::asio::io_service>();
/*Do stuff until connection needs to be reset*/
service_ptr->stop();
//I don't know your specific use case, but the call to io_service's member function reset is probably unnecessary.
//service_ptr->reset();
service_ptr.reset();//"reset" is a member function of unique_ptr, will delete object.
/*For your later check*/
if(service_ptr) //returns true if a valid object exists in the pointer
if(!service_ptr) //returns true if no object is being pointed to.
Generally speaking, you should never directly call ~object_name();. Ever. Ever. Ever. There's several reasons why:
As a normal part of Stack Unwinding, this will get called anyways when the method returns.
deleteing a pointer will call it.
"Smart Pointers" (like std::unique_ptr and std::shared_ptr) will call it when they self-destruct.
Directly calling ~object_name(); should only ever be done in rare cases, usually involving Allocators, and even then, there are usually cleaner solutions.
I have MessagesViewer frame that I want to control the uniqueness of,
with this piece of code:
MessagesViewer* m_pMsgViewer = NULL;
void Application::ShowMessagesViewer()
{
if (m_pMsgViewer == NULL)
{
m_pMsgViewer = new MessagesViewer(
wxGetApp().GetContainer()->GetAppData()->GetMessages()
);
}
else
{
m_pMsgViewer->FillPage(wxGetApp().GetContainer()->GetAppData()->GetMessages());
m_pMsgViewer->SetFocus();
}
}
But when I call this for the first time, m_pMsgViewer starts to refer to valid data in the memory. When I close MessagesViewer frame, it destroys it automatically, but the pointer is still referencing to old address, and I can't control destroying the frame from this client code.
How can I dereference a pointer to destroyed frame?
#bogdan already proposed a good solution, but there is another, even more automatic one: store your frame pointer in wxWeakRef<> instead. I.e. keep exactly the same code as now but replace the declaration with
wxWeakRef<MessagesViewer> m_pMsgViewer;
The weak reference will be automagically reset to NULL when the window is destroyed.
One solution is to set m_pMsgViewer back to nullptr when MessagesViewer is closed. A safe way to do that is to add a handler for wxEVT_CLOSE_WINDOW to your frame. For example, add the following code to MessagesViewer's constructor:
Bind(wxEVT_CLOSE_WINDOW, [](wxCloseEvent& evt)
{
m_pMsgViewer = nullptr;
evt.Skip();
});
evt.Skip() lets the event propagate further to the default handler provided by wx.
This simple example assumes that m_pMsgViewer is a global variable. If it's actually contained within the Application object, you'll have to add some way to access it.
The obvious alternative of adding such code to MessagesViewer's destructor is not a very good idea, as the actual destruction of the MessagesViewer object is delayed according to the docs, so it would be theoretically possible for Application::ShowMessagesViewer() to call FillPage() on a frame that has been closed and marked for destruction but not actually destroyed yet.
Handling the close event resets the pointer early on, thus avoiding the problem above.
You need to mark somehow that MessagesViwer has been destroyed and cannot be referenced any more. This means some extra info in addition to m_pMsgViewer.
I have a class which calls an asynchronous task using std::async in his constructor for loading its content. ( I want the loading of the object done asynchronously )
The code looks like this:
void loadObject(Object* object)
{
// ... load object
}
Object::Object():
{
auto future = std::async(std::launch::async, loadObject, this);
}
I have several instances of these objects getting created and deleted on my main thread, they can get deleted any time, even before their loading has finished.
I'd like to know if it is dangerous to having object getting destroyed when it is still getting handled on another thread. And how can I stop the thread if the object gets destroyed ?
EDIT: The std::future destructor does not block my code with the VS2013's compiler that I am using due to a bug.
As MikeMB already mentioned, your constructor doesn't finish until the load has been completed. Check this question for how to overcome that: Can I use std::async without waiting for the future limitation?
I'd like to know if it is dangerous to having object getting destroyed when it is still getting handled on another thread.
Accessing object's memory after deletion is certainly dangerous, yes. The behaviour will be undefined.
how can I stop the thread if the object gets destroyed ?
What I recommend you to take care of first, is to make sure that the object doesn't get destroyed while it's still being pointed at by something that is going to use it.
One approach is to use a member flag signifying completed load that is updated in the async task and checked in the destructor and synchronize the access with a condition variable. That will allow the destructor to block until the async task is complete.
Once you've managed to prevent the object from being destroyed, you can use another synchronized member flag to signify that the object is being destroyed and skip the loading if it's set. That'll add synchronization overhead but may be worth it if loading is expensive.
Another approach which avoids blocking destructor is to pass a std::shared_ptr to the async task and require all Object instances to be owned by a shared pointer. That limitation may not be very desireably and you'll need to inherit std::enable_shared_from_this to get the shared pointer in the constructor.
There is nothing asynchronous happening in your code, because the constructor blocks until loadObject() returns (The destructor of a future returned by std::async implicitly joins).
If it would not, it would depend on how you have written your code (and especially your destructor), but most probably, your code would incur undefined behavior.
Yes it is dangerous to having object getting destroyed when it is still getting handled on another thread
You can implement a lot of strategies actually depending on requirements and desired behaviour.
I would implement sort of pimpl strategy here, that means that all actual data will be stored in the pointer that your object holds. You will load all the data to the data-pointer-object and store it in the public-object atomically.
Techincally speaking object should be fully constrcuted and ready to use by the time the constrcutor is finished. In your case data-pointer-object will still probably be not ready to use. And you should make your class to handle correctly that state.
So here we go:
class Object
{
std::shared_ptr<Object_data> d;
Object::Object():
d(std::make_shared<Object_data>())
{
some_futures_matser.add_future(std::async(std::launch::async, loadObject, d));
}
}
Then you make atomic flag in your data-object that will signal that loading is complete and object is ready to use.
class Object_data
{
// ...
std::atomic<bool> loaded {false};
};
loadObject(std::shared_ptr<Object_data> d)
{
/// some load code here
d->loaded = true;
}
You have to check if your object is constrcuted every time when you acces it (with thread safe way) through loaded flag
I know very little about COM, and searching Google for COM somhow did not find COM at all (probably because it searched .com address instead).
We are using a video capturing hardware. Its SDK allows us to register a callback when a frame is captured. An object interface is passed as a parameter to that callback, and we can get the large buffer address (to the captured frame pixels) and other information by querying to that object.
Now, it looks like calling Release() does not actually delete the memory but decreases the reference count, and when the count reaches 0, it is deleted, right? So, about that large buffer address mentioned above, how about "delete"ing the buffer using the "delete" keyword?
It seems that our program (not written by me, and the person who wrote the program quit the company) copies the pointer to the buffer into some class but never calls any Release() in the callback. Later, the buffer is "delete'd in the class. It seems Release()ing the frame interface object also deletes the buffer. But are they the same?
COM somehow counts the reference but what happens if user's code just deletes that memory? I am sorry if my question is obscure. In short, is it safe to delete a buffer that was gotten from a COM object.
Simplified code: Suspicious situation
void mycallback(IFrame f)
{
char* buffer;
f->GetBuffer(buffer);
MyClass m(buffer);
...
}
MyClass::DeleteBuffer()
{
delete m_buffer;
}
When the code copies the frame buffer content into its own buffer then nothing special happened. The frame buffer is still owned by the COM code, the code's own buffer is still owned by that code. Do not delete the COM buffer, that will invoke undefined behavior when the COM code deletes it too. You should only ever call Release() on a COM interface pointer if you called AddRef() first. In a scenario like this, the AddRef() call was made by the COM code before it invoked the callback. And the Release() call will be made after the callback returns.
Seeing a frame getting copied in a callback is quite normal, the frame buffer normally only stays valid for the duration of the callback. So you have to copy it if you use it later.
If you are chasing a memory leak then this is not likely the culprit. If there was a reference counting problem on the frame buffer then the program couldn't last for more than a minute before having consumed all available memory.
Try to use this place operator delete, CoTaskMemFree
Dealing with COM interfaces is more trickier :-)
Make sure you match the IUnknown::AddRef() and IUnknown::Release() calls
As long as you are in the same context, you can delete the buffer explicitly, even though you got them from a COM interface. But make sure you nullify the pointer after deletion, so that there is no post handling issues.
MyClass::DeleteBuffer()
{
if(m_buffer)
{
delete m_buffer;
m_buffer = null;
}
}
In general, if you have a class that inherits from a Thread class, and you want instances of that class to automatically deallocate after they are finished running, is it okay to delete this?
Specific Example:
In my application I have a Timer class with one static method called schedule. Users call it like so:
Timer::schedule((void*)obj, &callbackFunction, 15); // call callbackFunction(obj) in 15 seconds
The schedule method creates a Task object (which is similar in purpose to a Java TimerTask object). The Task class is private to the Timer class and inherits from the Thread class (which is implemented with pthreads). So the schedule method does this:
Task *task = new Task(obj, callback, seconds);
task->start(); // fork a thread, and call the task's run method
The Task constructor saves the arguments for use in the new thread. In the new thread, the task's run method is called, which looks like this:
void Timer::Task::run() {
Thread::sleep(this->seconds);
this->callback(this->obj);
delete this;
}
Note that I can't make the task object a stack allocated object because the new thread needs it. Also, I've made the Task class private to the Timer class to prevent others from using it.
I am particularly worried because deleting the Task object means deleting the underlying Thread object. The only state in the Thread object is a pthread_t variable. Is there any way this could come back to bite me? Keep in mind that I do not use the pthread_t variable after the run method finishes.
I could bypass calling delete this by introducing some sort of state (either through an argument to the Thread::start method or something in the Thread constructor) signifying that the method that is forked to should delete the object that it is calling the run method on. However, the code seems to work as is.
Any thoughts?
I think the 'delete this' is safe, as long as you don't do anything else afterwards in the run() method (because all of the Task's object's member variables, etc, will be freed memory at that point).
I do wonder about your design though... do you really want to be spawning a new thread every time someone schedules a timer callback? That seems rather inefficient to me. You might look into using a thread pool (or even just a single persistent timer thread, which is really just a thread pool of size one), at least as an optimization for later. (or better yet, implement the timer functionality without spawning extra threads at all... if you're using an event loop with a timeout feature (like select() or WaitForMultipleObjects()) it is possible to multiplex an arbitrary number of independent timer events inside a single thread's event loop)
There's nothing particularly horrible about delete this; as long as you assure that:the object is always dynamically allocated, andno member of the object is ever used after it's deleted.
The first of these is the difficult one. There are steps you can take (e.g. making the ctor private) that help, but nearly anything you do can be bypassed if somebody tries hard enough.
That said, you'd probably be better off with some sort of thread pool. It tends to be more efficient and scalable.
Edit: When I talked about being bypassed, I was thinking of code like this:
class HeapOnly {
private:
HeapOnly () {} // Private Constructor.
~HeapOnly () {} // A Private, non-virtual destructor.
public:
static HeapOnly * instance () { return new HeapOnly(); }
void destroy () { delete this; } // Reclaim memory.
};
That's about as good of protection as we can provide, but getting around it is trivial:
int main() {
char buffer[sizeof(HeapOnly)];
HeapOnly *h = reinterpret_cast<HeapOnly *>(buffer);
h->destroy(); // undefined behavior...
return 0;
}
When it's direct like this, this situation's pretty obvious. When it's spread out over a larger system, with (for example) an object factory actually producing the objects, and code somewhere else entirely allocating the memory, etc., it can become much more difficult to track down.
I originally said "there's nothing particularly horrible about delete this;", and I stand by that -- I'm not going back on that and saying it shouldn't be used. I am trying to warn about the kind of problem that can arise with it if other code "Doesn't play well with others."
delete this frees the memory you have explicitly allocated for the thread to use, but what about the resources allocated by the OS or pthreads library, such as the thread's call stack and kernel thread/process structure (if applicable)? If you never call pthread_join() or pthread_detach() and you never set the detachstate, I think you still have a memory leak.
It also depends on how your Thread class is designed to be used. If it calls pthread_join() in its destructor, that's a problem.
If you use pthread_detach() (which your Thread object might already be doing), and you're careful not to dereference this after deleting this, I think this approach should be workable, but others' suggestions to use a longer-lived thread (or thread pool) are well worth considering.
If all you ever do with a Task object is new it, start it, and then delete it, why would you need an object for it anyway? Why not simply implement a function which does what start does (minus object creation and deletion)?