(not) using std::string in exceptions

前端 未结 2 864
猫巷女王i
猫巷女王i 2020-12-28 14:44

I\'m always reading that I should not to throw a std::string or some other classes allocating memory. like here or more importantly here on point 3. - D

2条回答
  •  生来不讨喜
    2020-12-28 15:28

    While I think not using std::string for core, fundamental exceptions may be a good guideline, I don't think user-facing libraries/applications should necessarily follow this.

    There may be other reasons, but you hit on the primary one: you'd like to indicate to the user (or developer) contextually meaningful information, which you often cannot do with a mere literal string. A dynamic allocation must occur in order to do this. If, for some reason, you had a bad_alloc, you're probably already hosed to begin with, so it doesn't buy/lose you anything.

    Edit:

    By the way: the destructor of std::exception is marked as virtual for a reason!

提交回复
热议问题