What to do for an error return for a struct object?

I have a function that returns a struct. If and else statement. How do I write it with one return without unnecessary stuff since I can't return a null object?
Can you show your current code?
Are you making a struct to return or are you simply trying to return a reference to an object.
I am returning a pointer 'this', but isn't that an object?
Last edited on
Well here are some partial pseudo code possibilities, there is probably more ways doing of this but here are some.

The this pointer points to the internals of a class or struct, which are objects.

Return nullptr or this. Check if it's not nullptr after calling to ensure safety.

1
2
3
4
5
6
7
8
type* getStruct() {
    if (condition) {
        return this;
    }
    else {
        return nullptr;
    }
}


Using an exception and then when you call it you check for exception.
1
2
3
4
5
6
7
8
type& getStruct() {
    if (condition) {
        return *this;
    }
    else {
        throw std::logic_error("invalid condition");
    }
}


Pass in an object and assign to this otherwise assign nullpltr. Then you could check after the pointer you passed in after calling.
1
2
3
4
5
6
7
8
void getStruct(type* obj) {
    if (condition) {
        obj = this;
    }
    else {
        obj = nullptr;
    }
}


I'd probably choose the first one but there could be a better way.
Last edited on
What if it is *this instead of this?
Topic archived. No new replies allowed.