[英]Using RAII with a character pointer
I see a lot of RAII example classes wrapping around file handles. 我看到很多RAII示例类包装文件句柄。
I have tried to adapt these examples without luck to a character pointer. 我试图在没有运气的情况下将这些示例适用于字符指针。
A library that I am using has functions that take the address of a character pointer (declared like get_me_a_string(char **x)). 我正在使用的库具有获取字符指针地址的函数(声明为get_me_a_string(char ** x))。 These functions allocate memory for that character pointer and leave it up to the end user of the library to clean it up in their own code.
这些函数为该字符指针分配内存,并将其留给库的最终用户,以便在自己的代码中清理它。
So, I have code that looks like this... 所以,我的代码看起来像这样......
char* a = NULL;
char* b = NULL;
char* c = NULL;
get_me_a_string(&a);
if(a == NULL){
return;
}
get_me_a_beer(&b);
if(b == NULL){
if(a != NULL){
free(a);
}
return;
}
get_me_something(&c);
if(c == NULL){
if(a != NULL){
free(a);
}
if(b != NULL){
free(b);
}
return;
}
if(a != NULL){
free(a);
}
if(b != NULL){
free(b);
}
if(a != NULL){
free(b);
}
It sounds like RAII is the answer for this mess that I have above. 听起来RAII就是我上面这个烂摊子的答案。 Could someone provide a simple C++ class that wraps a char* rather than a FILE*?
有人可以提供一个简单的C ++类来包装char *而不是FILE *吗?
Thanks 谢谢
There's something available already in the standard library: it's called std::string
. 标准库中已有一些东西可用:它叫做
std::string
。
Edit: In light of new information: 编辑:根据新信息:
It will allocate memory and fill it up.
它将分配内存并填满。 I could copy the contents into a new std::string object but I'd still have to free the memory that was allocated by the function.
我可以将内容复制到一个新的std :: string对象中,但我仍然必须释放该函数分配的内存。
This is poor design on the implementor's part -- the module that allocates should be responsible for deallocation. 这是实现者部分的糟糕设计 - 分配的模块应该负责解除分配。
Okay, now that I've got that out of my system: you could use a boost::shared_ptr
for freeing. 好的,现在我已经从我的系统中得到了它:你可以使用
boost::shared_ptr
来释放。
template<typename T>
struct free_functor
{
void operator() (T* ptr)
{
free(ptr);
ptr=NULL;
}
};
shared_ptr<X> px(&x, free_functor());
A very basic implementation (that you should make noncopyable etc). 一个非常基本的实现(你应该使noncopyable等)。
struct CharWrapper {
char* str;
CharWrapper(): str() {} // Initialize NULL
~CharWrapper() { free(str); }
// Conversions to be usable with C functions
operator char**() { return &str; }
operator char*() { return str; }
};
This is technically not RAII, as proper initialization happens later than at the constructor, but it will take care of cleanup. 这在技术上不是RAII,因为正确的初始化发生的时间晚于构造函数,但它将负责清理。
You could try something like this: 你可以尝试这样的事情:
template <typename T>
class AutoDeleteArray
{
public:
explicit AutoDeleteArray(const T* ptr)
: ptr_(ptr)
{}
~AutoDeleteArray()
{
delete [] ptr_;
// if needed use free instead
// free(ptr_);
}
private:
T *ptr_;
};
// and then you can use it like:
{
char* a = NULL;
get_me_a_string(&a);
if(a == NULL)
return;
AutoDeleteArray<char> auto_delete_a(a);
}
It is not the most reliable solution, but could be enough for the purpose. 它不是最可靠的解决方案,但可能足够用于此目的。
PS: I'm wondering would std::tr1::shared_ptr
with custom deleter work as well? PS:我想知道
std::tr1::shared_ptr
与自定义删除工作一样吗?
i think auto_ptr is what you want 我认为auto_ptr是你想要的
or boost shared_ptr if the auto_ptr semantics dont work for you 如果auto_ptr语义不适合你,则提升shared_ptr
对本地数组使用plain std::string
或boost :: scoped_array ,对于共享字符串使用boost :: shared_array (后者允许您提供自定义删除以调用free()
。)
Thanks everyone for your answers. 谢谢大家的回答。
Unfortunately, I cannot use boost, or other libraries on this project... so all of those suggestions are useless to me. 不幸的是,我不能在这个项目中使用boost或其他库...所以这些建议对我来说都是无用的。
I have looked at things like exception handling in C like here... http://www.halfbakery.com/idea/C_20exception_20handling_20macros 我在这里看过像C这样的异常处理之类的东西...... http://www.halfbakery.com/idea/C_20exception_20handling_20macros
And then I looked at why C++ doesn't have a finally like Java does and came across this RAII stuff. 然后我看了为什么C ++没有最终像Java一样,并遇到了这个RAII的东西。
I'm still not sure if I will go the destructor way and make the code C++ only, or stick with C exception macro's (which use the dreaded goto:) 我仍然不确定我是否会采用析构函数方式并仅使用C ++代码,或者坚持使用C异常宏(使用可怕的goto :)
Tronic suggested something like the following. Tronic建议如下。 With RAII, or destructors in general, are they supposed to be segfault proof?
对于RAII或一般的析构函数,它们应该是段错误证明吗? I'm guessing not.
我猜不是。
The only thing that I don't like is the fact that I now have to use a cast (char*) in my printf statements. 我唯一不喜欢的是我现在必须在我的printf语句中使用强制转换(char *)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct CharWrapper {
char* str;
CharWrapper(): str() {} // Initialize NULL
~CharWrapper() {
printf("%d auto-freed\n", str);
free(str);
}
// Conversions to be usable with C functions
operator char*() { return str; }
operator char**() { return &str; }
};
// a crappy library function that relies
// on the caller to free the memory
int get_a_str(char **x){
*x = (char*)malloc(80 * sizeof(char));
strcpy(*x, "Hello there!");
printf("%d allocated\n", *x);
return 0;
}
int main(int argc, char *argv[]){
CharWrapper cw;
get_a_str(cw);
if(argc > 1 && strcmp(argv[1], "segfault") == 0){
// lets segfault
int *bad_ptr = NULL;
bad_ptr[8675309] = 8675309;
}
printf("the string is : '%s'\n", (char*)cw);
return 0;
}
An alternative solution would be something like this, which is how I would write this code in C: 另一种解决方案是这样的,这就是我在C中编写这段代码的方式:
char* a = NULL;
char* b = NULL;
char* c = NULL;
get_me_a_string(&a);
if (!a) {
goto cleanup;
}
get_me_a_beer(&b);
if (!b) {
goto cleanup;
}
get_me_something(&c);
if (!c) {
goto cleanup;
}
/* ... */
cleanup:
/* free-ing a NULL pointer will not cause any issues
* ( see C89-4.10.3.2 or C99-7.20.3.2)
* but you can include those checks here as well
* if you are so inclined */
free(a);
free(b);
free(c);
Since you are saying you can't use boost, it isn't very hard to write a very simple smart pointer which doesn't share or transfer resources. 既然你说你不能使用boost,那么写一个不共享或传输资源的非常简单的智能指针并不是很难。
Here's something basic. 这是基本的东西。 You can specify a deleter functor as a template parameter.
您可以将删除器仿函数指定为模板参数。 I'm not particularly fond of conversion operators, so use the get() method instead.
我不是特别喜欢转换运算符,所以请改用get()方法。
Add other methods like release() and reset() at will. 随意添加其他方法,如release()和reset()。
#include <cstdio>
#include <cstring>
#include <cstdlib>
struct Free_er
{
void operator()(char* p) const { free(p); }
};
template <class T, class Deleter>
class UniquePointer
{
T* ptr;
UniquePointer(const UniquePointer&);
UniquePointer& operator=(const UniquePointer&);
public:
explicit UniquePointer(T* p = 0): ptr(p) {}
~UniquePointer() { Deleter()(ptr); }
T* get() const { return ptr; }
T** address() { return &ptr; } //it is risky to give out this, but oh well...
};
void stupid_fun(char** s)
{
*s = static_cast<char*>(std::malloc(100));
}
int main()
{
UniquePointer<char, Free_er> my_string;
stupid_fun(my_string.address());
std::strcpy(my_string.get(), "Hello world");
std::puts(my_string.get());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.