I'm wrapping part of the FBX SDK (closed, with a public API) with Mono (so COM, CLI aren't options) and a bunch of extern's, and it was all going well until I had to return a non-pointer instance. See here
The crucial point is that I have to return it back to C++ for another call. Because I don't know how you'd do that without a pointer, I returned it as such:
FBXAPI FbxProperty* Object_GetFirstProperty(FbxObject* obj)
{
return &obj->GetFirstProperty();
}
..and it's not until I try something like the next snippet that I get the "System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt." message.
FBXAPI const wchar_t* Property_GetName(FbxProperty* prop)
{
int c = prop->GetSrcPropertyCount();
return L"Test";
}
If I use almost identical code using the same calls in C++, it's fine. I've done another ~20 function calls in the same manner but without having to "pointerfy" it, and they're all fine too, so I don't think my DllImport's are to blame. So if the reference is to be blame, how else do I do it? Surely I don't store a global static reference somewhere just because someone called it from the API?
Any help is appreciated, C/C++ and the explicit way it handles memory is new to me.
I assume your program is crashing because the property you were getting the pointer to does no longer exist. Let me clarify and start by dissecting the following:
FBXAPI FbxProperty* Object_GetFirstProperty(FbxObject* obj)
{
return &obj->GetFirstProperty();
}
I looked up the documentation of FBX, and FbxObject::GetFirstProperty() has a return type of FbxProperty. Notice that the return value isn't any pointer or reference? That means you get a so called 'auto-variable', or in this case a 'temporary'. This kind of object only lasts until you leave the scope, which in this case is your Object_GetFirstProperty() of your wrapper. After that, the object is cleaned up and removed from the memory stack. FbxObject::GetFirstProperty() gives you a copy of the property, not an actual reference. Internally it might be different, but your wrapper is concerned about the property object itself, not it's content.
So what you are doing is you get a pointer to an address that is no longer valid later on when you pass it to your Property_GetName().
C++ behaves differently than C# in regards to object lifetime. An object in C# called MyObj can be thought of as a C++ pointer type like MyObject* - it's a like a reference value. In C# you have also value-types like struct and so forth, which are the equivalent to the C++ auto-variable. All auto-variables are destroyed when their lifetime scope is left.
What you'd have to do to overcome your problem is to save the object you get from FbxObject::GetFirstProperty() directly, and not a pointer to it. You'd basically have to marshall the object into a proper .NET class so that it's contents are not lost.
Alternatively, you could just allocate dynamic memory and copy the object you get from FbxObject::GetFirstPoperty() there, and return a pointer to your own memory. Of course you'd have to delete this memory later on manually. Here is a simple example:
FBXAPI FbxProperty* Object_GetFirstProperty(FbxObject* obj)
{
// Allocate custom memory.
char* myMem = new char[sizeof(FbxProperty)];
// Copy the property's content there.
std::memcpy(myMem, &obj->GetFirstProperty(), sizeof(FbxProperty));
// Return custom memory address.
return reinterpret_cast<FbxProperty*>(myMem);
}
This should solve your memory corruption issue. But in C++ you'd have to free this memory manually when your are finished with the property by doing ths:
FBXAPI void Property_Free(FbxProperty* prop)
{
// Free previously allocated memory
delete[] prop;
}
But this attempt may cause other problems, depending on how the actual FbxProperty handles it's data inside. You are creating a copy of the object, sure, but if the original temporaty/auto-variable deletes important memory upon destruction, you would have similar issus to the ones you have now.
If you are REALLY witty you could just write real wrapper classes for every FBX type you require and marshall the whole class type instead of generating separete C functions you have to P/Invoke every time you want to get a value or a property.
Related
Is it allowed to delete this; if the delete-statement is the last statement that will be executed on that instance of the class? Of course I'm sure that the object represented by the this-pointer is newly-created.
I'm thinking about something like this:
void SomeModule::doStuff()
{
// in the controller, "this" object of SomeModule is the "current module"
// now, if I want to switch over to a new Module, eg:
controller->setWorkingModule(new OtherModule());
// since the new "OtherModule" object will take the lead,
// I want to get rid of this "SomeModule" object:
delete this;
}
Can I do this?
The C++ FAQ Lite has a entry specifically for this
https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
I think this quote sums it up nicely
As long as you're careful, it's OK for an object to commit suicide (delete this).
Yes, delete this; has defined results, as long as (as you've noted) you assure the object was allocated dynamically, and (of course) never attempt to use the object after it's destroyed. Over the years, many questions have been asked about what the standard says specifically about delete this;, as opposed to deleting some other pointer. The answer to that is fairly short and simple: it doesn't say much of anything. It just says that delete's operand must be an expression that designates a pointer to an object, or an array of objects. It goes into quite a bit of detail about things like how it figures out what (if any) deallocation function to call to release the memory, but the entire section on delete (§[expr.delete]) doesn't mention delete this; specifically at all. The section on destructors does mention delete this in one place (§[class.dtor]/13):
At the point of definition of a virtual destructor (including an implicit definition (15.8)), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor’s class (see 8.3.5).
That tends to support the idea that the standard considers delete this; to be valid -- if it was invalid, its type wouldn't be meaningful. That's the only place the standard mentions delete this; at all, as far as I know.
Anyway, some consider delete this a nasty hack, and tell anybody who will listen that it should be avoided. One commonly cited problem is the difficulty of ensuring that objects of the class are only ever allocated dynamically. Others consider it a perfectly reasonable idiom, and use it all the time. Personally, I'm somewhere in the middle: I rarely use it, but don't hesitate to do so when it seems to be the right tool for the job.
The primary time you use this technique is with an object that has a life that's almost entirely its own. One example James Kanze has cited was a billing/tracking system he worked on for a phone company. When you start to make a phone call, something takes note of that and creates a phone_call object. From that point onward, the phone_call object handles the details of the phone call (making a connection when you dial, adding an entry to the database to say when the call started, possibly connect more people if you do a conference call, etc.) When the last people on the call hang up, the phone_call object does its final book-keeping (e.g., adds an entry to the database to say when you hung up, so they can compute how long your call was) and then destroys itself. The lifetime of the phone_call object is based on when the first person starts the call and when the last people leave the call -- from the viewpoint of the rest of the system, it's basically entirely arbitrary, so you can't tie it to any lexical scope in the code, or anything on that order.
For anybody who might care about how dependable this kind of coding can be: if you make a phone call to, from, or through almost any part of Europe, there's a pretty good chance that it's being handled (at least in part) by code that does exactly this.
If it scares you, there's a perfectly legal hack:
void myclass::delete_me()
{
std::unique_ptr<myclass> bye_bye(this);
}
I think delete this is idiomatic C++ though, and I only present this as a curiosity.
There is a case where this construct is actually useful - you can delete the object after throwing an exception that needs member data from the object. The object remains valid until after the throw takes place.
void myclass::throw_error()
{
std::unique_ptr<myclass> bye_bye(this);
throw std::runtime_exception(this->error_msg);
}
Note: if you're using a compiler older than C++11 you can use std::auto_ptr instead of std::unique_ptr, it will do the same thing.
One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.
Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.
It is allowed (just do not use the object after that), but I wouldn't write such code on practice. I think that delete this should appear only in functions that called release or Release and looks like: void release() { ref--; if (ref<1) delete this; }.
Well, in Component Object Model (COM) delete this construction can be a part of Release method that is called whenever you want to release aquisited object:
void IMyInterface::Release()
{
--instanceCount;
if(instanceCount == 0)
delete this;
}
This is the core idiom for reference-counted objects.
Reference-counting is a strong form of deterministic garbage collection- it ensures objects manage their OWN lifetime instead of relying on 'smart' pointers, etc. to do it for them. The underlying object is only ever accessed via "Reference" smart pointers, designed so that the pointers increment and decrement a member integer (the reference count) in the actual object.
When the last reference drops off the stack or is deleted, the reference count will go to zero. Your object's default behavior will then be a call to "delete this" to garbage collect- the libraries I write provide a protected virtual "CountIsZero" call in the base class so that you can override this behavior for things like caching.
The key to making this safe is not allowing users access to the CONSTRUCTOR of the object in question (make it protected), but instead making them call some static member- the FACTORY- like "static Reference CreateT(...)". That way you KNOW for sure that they're always built with ordinary "new" and that no raw pointer is ever available, so "delete this" won't ever blow up.
You can do so. However, you can't assign to this. Thus the reason you state for doing this, "I want to change the view," seems very questionable. The better method, in my opinion, would be for the object that holds the view to replace that view.
Of course, you're using RAII objects and so you don't actually need to call delete at all...right?
This is an old, answered, question, but #Alexandre asked "Why would anyone want to do this?", and I thought that I might provide an example usage that I am considering this afternoon.
Legacy code. Uses naked pointers Obj*obj with a delete obj at the end.
Unfortunately I need sometimes, not often, to keep the object alive longer.
I am considering making it a reference counted smart pointer. But there would be lots of code to change, if I was to use ref_cnt_ptr<Obj> everywhere. And if you mix naked Obj* and ref_cnt_ptr, you can get the object implicitly deleted when the last ref_cnt_ptr goes away, even though there are Obj* still alive.
So I am thinking about creating an explicit_delete_ref_cnt_ptr. I.e. a reference counted pointer where the delete is only done in an explicit delete routine. Using it in the one place where the existing code knows the lifetime of the object, as well as in my new code that keeps the object alive longer.
Incrementing and decrementing the reference count as explicit_delete_ref_cnt_ptr get manipulated.
But NOT freeing when the reference count is seen to be zero in the explicit_delete_ref_cnt_ptr destructor.
Only freeing when the reference count is seen to be zero in an explicit delete-like operation. E.g. in something like:
template<typename T> class explicit_delete_ref_cnt_ptr {
private:
T* ptr;
int rc;
...
public:
void delete_if_rc0() {
if( this->ptr ) {
this->rc--;
if( this->rc == 0 ) {
delete this->ptr;
}
this->ptr = 0;
}
}
};
OK, something like that. It's a bit unusual to have a reference counted pointer type not automatically delete the object pointed to in the rc'ed ptr destructor. But it seems like this might make mixing naked pointers and rc'ed pointers a bit safer.
But so far no need for delete this.
But then it occurred to me: if the object pointed to, the pointee, knows that it is being reference counted, e.g. if the count is inside the object (or in some other table), then the routine delete_if_rc0 could be a method of the pointee object, not the (smart) pointer.
class Pointee {
private:
int rc;
...
public:
void delete_if_rc0() {
this->rc--;
if( this->rc == 0 ) {
delete this;
}
}
}
};
Actually, it doesn't need to be a member method at all, but could be a free function:
map<void*,int> keepalive_map;
template<typename T>
void delete_if_rc0(T*ptr) {
void* tptr = (void*)ptr;
if( keepalive_map[tptr] == 1 ) {
delete ptr;
}
};
(BTW, I know the code is not quite right - it becomes less readable if I add all the details, so I am leaving it like this.)
Delete this is legal as long as object is in heap.
You would need to require object to be heap only.
The only way to do that is to make the destructor protected - this way delete may be called ONLY from class , so you would need a method that would ensure deletion
I have a nasty bug in my C++ project. There's a class
class SomeClass {
...
std::string *someString;
...
}
Here's a constructor
SomeClass(...) {
...
someString = new std::string("");
...
}
And the thing is that afterwards I operate only with that specific string, without modifying the poiner value. I assign to that string different strings all the time, like
*someString = "whatever";
someString->assign("whatever");
*someString += 'a';
Application is multithreaded and there's a really nasty glitch. At some point, application crashes. Debugger shows that variable someString has A BAD POINTER. And I have no idea how this is possible
delete someString;
IS NEVER CALLED.
I've looked to all the references of that string pointer and here's what I can tell you:
delete on that pointer is never called.
that pointer is never assigned to anything else (where it may be deleted later).
pointer value of that string is never altered in any way (debugger shows 'Bad Ptr').
other class variables seem fine like they are supposed to be.
Therefore, I need to find a way to check when a destructor is called on a specific object. In fact, array of objects.
So, is there a way to set a breakpoint on a destructor (or any other method) on a specific set of objects (I'm working on visual studio 2010 proffessional)?
If you are multithreading, consider implementing a locking mechanism ... (if you didn't do it already) for your string member. Highly possible one thread tries to write to a pointer which is being reallocated in a different thread... or something like this. A little bit more code would help us to understand the problem in a deeper context.
I have been trying to find a reason why this does not work in my code - I think this should work. Here is an excerpt from a header file:
#define WARN_UNUSED __attribute__((warn_unused_result))
class Trans {
Vector GetTranslation() const WARN_UNUSED {
return t;
}
};
So my question is: why don't I get a warning when I compile code with something like:
Gt.GetTranslation();
?
Thanks for the help.
The purpose of this attribute is intended (but not exclusively) for pointers to dynamically allocated data.
It gives a compile-time garantee that the calling code will store the pointer in a variable (may as a parameter to a function too ,but that I'm not certain of) en thereby delegates the responsibility of freeing\releasing\deleting the object it points to.
This in order to prevent memory leakage and\or other lifetime controlling aspects.
for instance ,if you call malloc( ... ) without storing the pointer ,you are not able to free it it afterwards. (malloc should have this attribute)
If you use it on function return an object ,than the mechanism is meaningless because the object that is returned is stored in a temporary and may be copied to a non-temporary variable (might be optimized out) and will always be destructed (because it will.
BTW , it's not particulary usefull for returned references (unless you code is aware of it and requires some kind of release mechanism) ,since the referenced object doesn't get destructed when going out of scope.
I have two four classes:
MainClass (class where things start)
XmlReader (class used to parse an xml file)
SerialPortSettings (holds info about the serial port read from the xml-file, e.g. baud rate, comport etc)
SerialPortListener (takes a reference to a SerialPortSettings object in its constructor)
MainClass has a method to read things from an xml-file.
In this method, it first creates an instance of XmlReader and gives it an xml-file as a constructor parameter. This xmlReader does only need to exist within this method:
XmlReader xmlReader (xmlFile);
The xmlReader parsers the xmlFile. MainClass gets access the xml-stuff by calling get-methods in XmlReader. So far everything is good.
However, one of the methods XmlReader offers, is a method which creates an object of type SerialPortSettings based on the information read from the xml-file:
SerialPortSettings* XmlReader::getSerialPortSettings() {
.... // reading stuff from xml file
return new SerialPortSettings(baudRate, dataBits, comport);
}
This method is called from MainClass and the return value is stored in a pointer:
SerialPortSettings* settings = xmlReader.getSerialPortSettings();
The next thing the MainClass does is to create a SerialPortListener (which is a member-variable that has to exist until MainClass is exited). SerialPortListener takes a reference to a SerialPortSettings in it's constructor:
m_serialPortListener = new SerialPortListener(*settings);
Hence SerialPortSettings also has to exist until MainClass exits, therefore I have created this as a pointer.
So here is the clue:
In the SerialPortListener destructor I tried to delete the SerialPortSettings-object:
SerialPortListener::~SerialPortListener() {
delete &m_settings;
}
Then in the MainClass destructor I deleted the SerialPortListener-object:
MainClass::~MainClass() {
delete m_serialPortListener;
}
This fails. I get an error saying that I deleted something twice in the main-class:
*** glibc detected *** ./ioserver: double free or corruption (out): 0x00860d80 ***
When I remove the delete &m_settings from SerialPortListener, it works fine.
But when should pointer be deleted? What is the correct thing to do? I really want my xml-reader to create the SerialPortSettings - object, insted of returning all of the info (baud rate, comport etc) to MainClass and create the SerialPortSettings object itself.
A good solution is to simply let xmlReader::getSerialPortSettings return a SerialPortSettings by value.
Let the compiler do the optimization.
But where you do need to handle pointer lifetimes, do use smart pointers, such as std::auto_ptr or boost::shared_ptr. The key idea is to define ownership. The owner (which in the case of boost::shared_ptr is the collection of smart pointers referring to the object) is responsible for deleting – no-one else.
Cheers & hth.,
The pointer should be deleted at the end of MainClass.
It makes no sense (to me, at least) to use delete on a reference.
It would be way cleaner to not have the XML reader create new objects; treat SerialPortSettings as a "dumb" container, and just pass in a reference to fill in with data from the XML:
XmlReader::getSerialPortSettings(SerialPortSettings& settings);
the actual instance can then be a local variable in the main program, and be passed (by const reference, this time) to the serial port when it's created:
SerialPortSettings portSettings;
m_xmlReader->getSerialPortSettings(portSettings);
m_serialPort = new SerialPort(portSettings);
the life time of the settings instance is then naturally the same as the scope it's in, since it's just a local variable.
If the method in the main class that reads XML needs to exit before the serial port goes out of scope, you could make the settings a member variable of the main class, instead.
What is the datatype of m_settings? Is it a SerialPortSettings* or a SerialPortSettings? If the latter, you can't delete it like that anyway, as it's allocated on the stack. If it's the former (a pointer), you do not need the reference operator. Simply write delete m_settings;
A simple typo in your delete:
delete &m_settings;
should be:
delete m_settings;
For any pointer you should decide who owns the pointer, and that should be who deletes it.
Or you can use a smart pointer such as shared_ptr and eliminate the problem altogether.
SerialPortListener::~SerialPortListener() {
delete &m_settings;
}
That block looks quite weird. Are you sure you aren't trying to delete value by reference? Cause C++ does it automatically when you delete the class, so your delete is really trying to delete twice.
OK, first of all, you're missing the truly important bit of information which is HOW is SerialPortListener::m_settings being stored. Because of the error you're getting, I'm guessing you're actually storing a copy of it, which means: I bet you have something like this:
class SerialPortListener {
SerialPortSettings m_settings;
SerialPortListener(SerialPortSettings set) {
m_settings = set;
}
}
if it's something similar to this, then the listener is saving a copy of the object in it's own memory, and deleting it doesn't make sense, since it's not a pointer. Rule of thumb, never do delete &anything until you know what you're doing and realize you really need to.
In terms of "correctness", the pointer should be freed by the main class, since it was who created it. Or if you don't have any use for it in the main class, and want the listener to delete it, save a pointer instead of an object or reference in the listener.
I ended up making m_serialPortSettings a pointer in SerialPortListener, and deleting it from there.
I can write a function this way in Objective-C. This can be used to churn out many UIButtons.
+(UIButton*)getButton:(CGRect)frame{
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Some title" forState:UIControlStateNormal];
button.frame=frame;
return button;
}
Can the same be done in C++? I am not asking about creation of UIButton in C++.
But churning out many objects with a help of a function as this:
CString getCstring(some parameters)
{
CString string = L"Hi sampe string.";
return string;
}
I think that the CString object that is created in this function would be in stack and may lose it value once goes out of this function.
In case of Objective-C code, we can retain the autoreleased object to use it. Is there any such mechanism available in C++?
In C++ you can do
CString* getCString(some parameters)
{
CString* string = new CString(L"Hi sample string.");
return string;
}
and delete (by calling delete on the pointer) the string in the caller after he is done with it if you want to have the string on the heap. However in the first version you posted, I see no problem. It is a stack variable, but of course it is still valid in the caller as it is the return value.
I think that the CString object that is created in this function would be in stack and may lose it value once goes out of this function.
It doesn’t lose its value since it will be copied (although the compiler can elide the copy as an optimization).
So don’t worry – this works just fine in C++.
You can also return a pointer to dynamically allocated memory but this makes usage harder since the client has to free the memory explicitly. In general this is not a good solution – handling raw pointers to dynamic memory is the #1 reason for memory leaks and cleaning such code up is horrible.
A better way is to use smart pointers (e.g. shared_ptr or unique_ptr) that take care of the memory management themselves.
Your string variable will eventually go out of scope, but return string; will return only the copy and hence you can use it in C++ as such now...
Your Obj-C code works against coding styles and memory management rules. It should look like:
+(UIButton*)buttonWithFrame:(CGRect)aRect {
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Some title" forState:UIControlStateNormal];
button.frame = aRect;
return button;
}
Seems like minor changes, but it makes memory managament (object ownership) obvious and names the parameter appropriately.