C++: Creating a shared object rather than a shared pointer to an object

我与影子孤独终老i 提交于 2019-12-01 19:30:00

The whole point of shared_ptr is that it (and its copies) own the object that it points to. If you want to give an A to a container that manages its lifetime then you shouldn't be using a shared_ptr at all as it doesn't meet your needs; HelpfulContainer only knows how to be the sole owner of a dynamically created object so you need to give it a pointer to an object that isn't owned by anything else.

I think that it is usually poor design for an object to care about its own lifetime (there are exceptions). It is usually more useful if an object can do a job and something else manages its creation and descruction, choosing the simplest lifetime strategy possible (e.g. local/automatic variable).

If you absolutely have to share ownership between two things that don't co-operate (such as shared_ptr and HelpfulContainer) then you will have to use some sort of proxy technique.

In this case, though, it just looks like HelpfulContainer just isn't that helpful for your situation.

I'm not sure what this does for you.

If helpfulContainer.eventHorizon() always deletes its parameter, then why not just pass a new copy of (the original) A class:

  helpfulContainer.eventHorizon(new A(sa1));

Or, if helpfulContainer.eventHorizon() only sometimes deletes its parameter, then making the call as

  helpfulContainer.eventHorizon(new SharedA(sa1)); 

will leak both the SharedA and the original A (sa1) on those occasions when it chooses not to delete.

So you are creating a Stand-In (SharedA) for which deletion is okay. Even though this is kinda awkward, I guess it's necessary to work with your legacy API. To slightly improve this: Allow construction of SharedA from a shared_ptr, but not the other way around - and then only use the SharedP when you absolutely must:

int main()
{
  HelpfulContainer helpfulContainer;

  boost::shared_ptr<A> sa1(new A(1));

  // deletes its parameter, but that's okay
  helpfulContainer.eventHorizon(new SharedA(sa1)); 
}

Implicit conversions to the underlying pointer type are inconsistent with the intended use of shared_ptr in that you can extremely easily pass the shared_ptr to a function etc without realizing it.

It sounds to me like HelpfulContainer is anything BUT helpful and should be fixed or ditched.

If that's not possible then probably the best way is to just copy the A you want to pass in and pass the copy to the container.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!