Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

c++ - Is it a Bad Idea to destructor and reconstruct an object in the assignment operator?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This approach is not new, and people have tried it before. The main problem, as stated in the comments (the rest is less serious) is a potential for exception thrown during the call to the copy constructor.

If that happens, you end up in a very bad situation - you did call destructor already, so that object is no longer valid, and there is no undoing that. Even if you catch the exception, there is still no good recourse, as there is nothing you can do to restore the object.

There are also classes which need a certain pre-condition before destructor can be called (std::thread is a prime example). While I personally do not like this, those classes exist.

If you are doing this for your own fully-controlled class, where you know for a fact copy-constructor doesn't throw (and ideally annotated as such), and random destructing of the class is acceptable, this approach is viable - although, usually not worth it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...