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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...