Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Does a unique_ptr call the destructor on its own?

Probably "dumb" question, but I failed to grasp this part of the concept.

Say I have a unique_ptr to a class object and a normal destructor ~Destructor.

my main is just creating the pointer and the object to which it points. If I do nothing else, does it call the destructor? Does it work like a 'new' pointer which doesn't call destructor unless you type delete?

question from:https://stackoverflow.com/questions/65922639/does-a-unique-ptr-call-the-destructor-on-its-own

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

1 Reply

0 votes
by (71.8m points)

std::unique_ptr will automatically call a deleter function when the unique_ptr is destroyed. By default that deleter function applies the C++ delete operator to the owned object which runs the destructor and frees the memory.

You can go wrong if you leak the unique_ptr instance itself (then it never has a chance to perform its cleanup), if you detach your object from the unique_ptr (that tells it not to do cleanup), or if you fail to match the deleter function to the original allocation method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...