[英]Should a library use an interface that uses smart pointers?
I'm starting to write a library and considering its interface. 我开始写一个库并考虑它的界面。 Previous libraries I've written all use raw pointers (both internally and in its interface), and now I want to try the smart pointer library that comes with VS2010.
我编写的以前的库都使用原始指针(内部和接口),现在我想尝试VS2010附带的智能指针库。
Please help :) 请帮忙 :)
It is imposable to answer those question without understanding a lot more about your design principles and how you expect the library to be used. 如果不了解更多关于您的设计原则以及您希望如何使用库,那么回答这些问题是不可能的。
So I can only answer based on my experience and how I like my libraries to be used. 所以我只能根据自己的经验以及我喜欢使用的库来回答。
For Example: 例如:
#if defined(MY_PROJ_SHARED_PTR_FROM_BOOST)
#include <boost/shared_ptr.hpp>
#define MY_PROJ_SHARED_PTR_NAMESPACE boost
#elif defined(MY_PROJ_SHARED_PTR_FROM_STD)
#include <memory>
#define MY_PROJ_SHARED_PTR_NAMESPACE std
#elif defined(MY_PROJ_SHARED_PTR_FROM_TR1)
#include <tr1/memory>
#define MY_PROJ_SHARED_PTR_NAMESPACE std::tr1
#else
#error "MY_PROJ_SHARED_PTR_FROM_<XXX> not defined correctly"
#endif
namespace X
{
using ::MY_PROJ_SHARED_PTR_NAMESPACE::shared_ptr;
}
int main()
{
X::shared_ptr<int> data;
}
I am sure there are other ways to do this. 我相信还有其他方法可以做到这一点。
But it is late. 但现在已经很晚了。
I would say to use 80-20 rule here. 我会说在这里使用80-20规则。 If 80% of clients would be better of using boost/stl/C++ compliant, then please do so.
如果80%的客户更好地使用boost / stl / C ++,那么请这样做。 For the rest, you can build adapter layer and move the complexity to that layer.
对于其余部分,您可以构建适配器层并将复杂性移动到该层。 The Adapter design pattern is my favourite for such purposes.
适配器设计模式是我最喜欢的用途。
From a user's point a view I'd say that you just need to be clear in your interface about what you need. 从用户的角度来看,我会说你只需要在界面中清楚地知道你需要什么。
Do you need a copy of the object or just a pointer? 您需要对象的副本还是指针?
Internally you can probably use the type of pointer that you're most convienant off as long as it don't degrade performance too much and don't cause bugs. 在内部,你可以使用你最有意义的指针类型,只要它不会降低性能太多并且不会导致错误。
A question to ask is what exactly will you do with that pointer? 要问的问题是你究竟会用指针做什么? Will you delete it?
你会删除吗? Can I change the reference if I update/delete the object (say in the case of a GUI library).
如果我更新/删除对象(例如在GUI库的情况下),我可以更改引用。
As someone who don't usually use smart pointers when they are not needed seeing too much smart pointers will just tell me you don't pay attention to what you will do and is cause for potential bugs. 作为一个通常不使用智能指针的人,当他们不需要看到太多的智能指针时,只会告诉我你不会注意你会做什么,并且是造成潜在错误的原因。
As a library user I prefer a crash (when attempting to dereference a clearly invalid pointer) to having an semi-valid pointer around that is not actually what I expect (which I suspect can be a problem with using smart pointers of the shared_ptr kind). 作为一个库用户,我更喜欢崩溃(当试图取消引用一个明显无效的指针)时,周围有一个半有效指针实际上并不是我所期望的(我怀疑使用shared_ptr类型的智能指针会有问题) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.