Ser*_*i G 8 c++ pointers api-design
假设我有一节课:
class Scheduler {
Scheduler(JobService *service);
AddJob(JobID id, ISchedule *schedule);
}
Run Code Online (Sandbox Code Playgroud)
构造函数接受指向服务的指针,但Scheduler不接受服务指针的所有权.假定服务指针由调用者释放.
AddJob案例正好相反.计划生存期由调度程序管理,当作业不再需要运行计划时,内存将被释放.
从API的角度来看,目前尚不清楚谁拥有指针的所有权以及谁没有.如果有一些技术可以通过API设计而不是通过文档来表明意图,那我就更聪明了.使它更加简单明了.
如果可以的话,我会构造ISchedule的实例,但它是C++(接口)中的抽象类,因此为每种类型的调度创建Add重载是不切实际的.所以,我必须在Add中加一个指针.
场景的数量不仅仅是两个。
class Scheduler {
// pass the raw pointer (or use a reference) to expresses
// no ownership transfer (The passed in object will no longer be
// needed after the pointer or reference becomes invalid)
Scheduler(JobService* service);
Scheduler(JobService& service);
// use a std::unique_ptr to pass ownership
AddJob(JobID id, std::unique_ptr<ISchedule> schedule);
// use a std::shared_ptr to pass shared ownership
// when the passed in object needs to outlive either the caller
// or the receiver and either one may need to delete it
SomethingElse1(std::shared_ptr<Stuff> stuff);
// use a std::weak_ptr to pass shared ownership
// when the object may, or may not outlive
// the receiver and the receiver needs to be able to detect
// if the pointer is still valid (like an intermittent service)
SomethingElse2(std::weak_ptr<Stuff> stuff);
};
Run Code Online (Sandbox Code Playgroud)
参考:
R.30 将智能指针作为参数仅用于显式表达生命周期语义
R.32使用 unique_ptr 参数来表示函数承担小部件的所有权
R.34带一个 shared_ptr 参数来表示一个函数是部分所有者
您没有任何选项(清除文档除外),以指示原始指针的所有权.
这就是c ++动态管理库的智能指针:
std::unique_ptr 将所有权传递给接收者std::shared_ptr 股东之间的所有权std::weak_ptr 表示依赖共享正如在@ Galik的精彩回答中指出的那样,可以使用专用引用来表示严格的生命依赖性.