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
345 views
in Technique[技术] by (71.8m points)

c++ - Unique_ptr destructor saying object has never been allocated

I have a main process that owns a Model object. The purpose of this is to share a Model between various objects that performs tasks and modifies the same Model.

Right now, I create a unique_ptr to this object and pass a reference to that unique_ptr to other objects to perform certain tasks.

The tasks all complete correctly, but something weird happens when it tries to call the destructor on the unique_ptr. It shows:

RAW: memory allocation bug: object at 0xd0ebdfb2b8 has never been allocated

Question:

  1. Why is this error happening?
  2. Is unique_ptr the right way to tackle this problem?

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

1. Why is this error happening?

Without seeing your code it is impossible to answer why this is happening.

2. Is unique_ptr the right way to tackle this problem?

According to Straustrup and Sutter's Core Guidlines

R.30: Take smart pointers as parameters only to explicitly express lifetime semantics

Reason: Accepting a smart pointer to a widget is wrong if the function just needs the widget itself. It should be able to accept any widget object, not just ones whose lifetimes are managed by a particular kind of smart pointer. A function that does not manipulate lifetime should take raw pointers or references instead.

You should only be passing a std::unique_ptr to a function if that function may need to alter its ownership. Otherwise you should pass the raw pointer or a reference to the object that the unique_ptr is managing.


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

...