如果使用没有shared_ptr的cpp,如何管理实例的生命周期和一对多所有权?有没有可以遵循的惯例?例如,DirectX有D3DDevice*,D3DDeviceContext* everywhere和mesh可以归sereval对象所有。
把它交给一个经理来保存它的生命周期,并总是通过ref传递它,这是一个好的解决方案吗?
C如何管理项目中的原始指针和所有权?
任何回复都将不胜感激。
发布于 2017-08-31 00:29:46
简而言之,std::shared_ptr通过与其所有副本协作,维护引用计数对其所包含指针的所有权。这意味着几个std::shared_ptr对象可以通过一个指针拥有同一个对象。当拥有该对象的最后一个剩余std::shared_ptr被销毁或分配另一个指针时,该对象将被销毁。
您可以使用RAII实现相同的功能,如下所示:
template<typename T> class MySharedPtr {
public:
MySharedPtr() : ref_count(new int(1)), obj_ptr(0) {
}
MySharedPtr(T* new_ptr) : ref_count(new int(1)), obj_ptr(new_ptr) {
}
MySharedPtr(const MySharedPtr<T>& other) :
ref_count(other.ref_count), obj_ptr(other.obj_ptr) {
(*ref_count)++;
}
~MySharedPtr() {
if(--(*ref_count) == 0) {
delete ref_count;
delete obj_ptr;
}
}
MySharedPtr<T>& operator=(const MySharedPtr<T>& other) {
if(this != &other) {
if(--(*ref_count) == 0) {
delete ref_count;
delete obj_ptr;
}
ref_count = other.ref_count;
obj_ptr = other.obj_ptr;
(*ref_count)++;
}
return *this;
}
T& operator*() { return *obj_ptr; }
T* operator->() { return obj_ptr; }
private:
int* ref_count;
T* obj_ptr;
};在c中,情况是一样的,您必须维护引用计数,并在引用计数变为零时释放托管空间。具有opaque pointer的示例可以如下所示:
示例.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
struct MyType;
struct MyType* new_MyType();
struct MyType* ref_MyType(struct MyType*);
struct MyType* unref_MyType(struct MyType*);
float MyType_getData(struct MyType*);
#endif /* EXAMPLE_H */example.c
#include "example.h"
#include <stdlib.h>
struct MyType {
int ref_count;
float some_data;
};
struct MyType* new_MyType() {
struct MyType* obj_ptr = (struct MyType*)malloc(sizeof(struct MyType));
obj_ptr->some_data = 0.0f;
obj_ptr->ref_count = 1;
}
struct MyType* ref_MyType(struct MyType* obj_ptr) {
if(obj_ptr == NULL)
return NULL;
obj_ptr->ref_count++;
return obj_ptr;
}
struct MyType* unref_MyType(struct MyType* obj_ptr) {
if(obj_ptr == NULL)
return NULL;
if(--(obj_ptr->ref_count) == 0) {
free(obj_ptr);
return NULL;
}
return obj_ptr;
}
float MyType_getData(struct MyType* obj_ptr) {
return (obj_ptr != NULL ? obj_ptr->some_data : 0.0f);
}https://stackoverflow.com/questions/24184236
复制相似问题