如何管理原始指针在CPP没有shared_ptr
how to manage raw pointers in cpp without shared_ptr?
如果我使用没有shared_ptr
的cpp,如何管理实例的生命周期和一对多所有权?有什么惯例可以遵循吗?例如,DirectX到处都有D3DDevice*
, D3DDeviceContext*
,网格可以由多个对象拥有。
把它放到一个管理器来保存它的生命时间,并且总是通过ref传递它,这是一个好的解决方案吗?
和C如何管理原始指针和所有权在一个项目?
欢迎回复
简而言之,std::shared_ptr
与它的所有副本一起保持引用计数对其包含的指针的所有权。这意味着几个std::shared_ptr
对象可以通过指针拥有同一个对象。当拥有该对象的最后一个std::shared_ptr
被销毁或被分配另一个指针时,上述对象将被销毁。
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中情况是一样的,您必须维护引用计数并在引用计数变为零时释放托管空间。使用不透明指针的示例如下:
example.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);
}
相关文章:
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- 是否可以使用 libclang python 解析 cpp 文件中没有标头的函数原型
- 在C++中使用没有合作伙伴Class/Cpp文件的头文件是否实用
- C2011: 'Card':"类"类型重新定义(尽管使用了包含保护并且没有在文件中重新定义.cpp类)
- 有没有办法让这个模板在 cpp 中工作?
- 有没有办法从 cpp 中的文本生成条形码图像?
- 如何在没有缓冲的情况下使用 parquet-cpp 写入面向流/行的数据?
- 在 cpp proj 中没有这样的文件 pyconfig.h
- 在没有多个定义的标头文件中包括一个CPP文件
- 我运行sudo g++ main.cpp,但它没有运行程序
- 有没有办法在Visual Studio中对CPP文件进行数字签名
- cpp 中的析构函数是否自动调用?即使析构函数没有提及非动态变量,它们也会被删除吗?
- 致命错误:auc_.cpp:2:10:致命错误:omp.h:没有此类文件或目录
- cpp 没有匹配的函数调用来调用构造函数.为什么
- Ubuntu C++ 编译器错误: g++: 错误: 文件.cpp: 没有这样的文件或目录
- 第一次从现有的main中编写头文件和.cpp;没有输出
- 为什么我的simpleVector.cpp没有链接?(从c++开始)
- 如何管理原始指针在CPP没有shared_ptr
- untiled2main .cpp:没有这样的文件或目录