NoSenseEtAl
NoSenseEtAl

Reputation: 30048

Exception handling and member variables

I have a simple Q.

If we have a class that has dynamically allocated member(or member that used dynamic allocation) and we often use that member what is the best way to handle some operation failing on that member.
Ofc there is try catch but Im not talking about that.

1) Im talking about the fact that now the member is in the state it shouldnt be(and here Im not talking about leaking resources, Im talking about the fact that for example we wanted to push_back 100 elements to std::vector but we only added 47).

And now for example when we call the other method sendToDB we will be sending 47 instead of 100 items to DB. My guesstimates for solving is to have bool return values on all public methods(trying to go for all or nothing(aka push_back all 100 or push 0) and return false if we do manage to push 100, false if we push 0.

2) But this still leaves the problem of the dynamically allocated members(for example shared_ptr). Does that mean that every method that uses it must do something like this:

bool MyClass::sendDataToDB()
{
    if (! m_DBConnection ) //m_DBConnection is std::shared_ptr
    return false;
   //...


}

Upvotes: 1

Views: 173

Answers (1)

BigBoss
BigBoss

Reputation: 6914

I don't fully understand your problem, but I get this:

In your class you have an storage( something like vector ) and then you want to insert something in it, and operation may fail in middle of it. So you want to know whether insertion failed or operation complete! am I right? If answer is yes, I think the best solution for this is something like iostream that set a fail state in case of failure and you can check it later or can throw exception but in any case, setting fail bit can signal every one that my object is in a failed state

Upvotes: 1

Related Questions