2

I'm an objective-C developer that's struggling with C++ code.

Below is the code I have in C++:

ULConnection *conn;
...... //code that builds up the connection
conn->GetLastError()->GetString(value, 255);

I need to create a local copy (not reference) of GetLastError().

How do I get a local reference and also check for null?

Here is my failed attempt:

ULError error = *conn->GetLastError();
if (&error != NULL){}
M.M
  • 138,810
  • 21
  • 208
  • 365
user1107173
  • 10,334
  • 16
  • 72
  • 117
  • 3
    Please show ALL relevant code, declarations, etc. What do you mean "copy of GetLastError?" It is a function. You mean the result that it returns? What error do you get? – OldProgrammer Jun 03 '15 at 00:31
  • 1
    Are you referring to [this function](http://dcx.sap.com/1201/en/ulc/ulc-ulcpp-ulconnection-cla-getlasterror-met.html) ? – M.M Jun 03 '15 at 00:34
  • Not clear what you mean. Objective-C is not anyhow different from C++ regarding pointer to objects. – c-smile Jun 03 '15 at 00:34
  • @MattMcNabb that's exactly the function. – user1107173 Jun 03 '15 at 00:42

2 Answers2

2

As per my understanding function conn->GetLastError() returns a pointer of ULError and need to check is the return pointer is null or not.

This will work for you.

const ULError *error = conn->GetLastError();
if (error){}

Since C++11 you can do as follows instead comparing with NULL

if( error != nullptr)
Steephen
  • 14,645
  • 7
  • 40
  • 47
  • 2
    If it is the same function as in [this page](http://dcx.sap.com/1201/en/ulc/ulc-ulcpp-ulconnection-cla-getlasterror-met.html) then OP will need to take care not to use this `error` pointer after the object it points to has been destroyed. The documentation describes it as being "valid while the connection is open". – M.M Jun 03 '15 at 00:38
  • 1
    @MattMcNabb maybe that's why he need a local copy :) – Sergi0 Jun 03 '15 at 00:40
  • If I run `ULError *error = conn->GetLastError();` the compiler complains "Cannot Initialize a variable type 'ULError *' with an rvalue of type `'const ULError *'` – user1107173 Jun 03 '15 at 00:43
  • @Steephen -- this issue is in the field and since I can't really reproduce it so I can't really check locally. Is there a way to make sure that your solution indeed provides a copy, and not a reference? – user1107173 Jun 03 '15 at 00:49
  • 2
    @user1107173 this solution does not make a copy. But there might be no way to make a copy, it depends on whether the people who made this API wanted copies to be possible, and their documentation doesn't say one way or the other. It would help to see the full class definition for `ULError` , there may be some hints in there. I couldn't find a download link for this API's headers. – M.M Jun 03 '15 at 00:51
-2

assuming that GetLastError returns a pointer

if (conn->GetLastError() != nullptr)
{
  ULError error = *(conn->GetLastError());
  // use the error
}
Sergi0
  • 1,084
  • 14
  • 28