我有一个分配内存然后返回指向该内存地址的指针的函数。我正在分配一个字符数组,它们传递给函数的参数将是数组大小。现在的问题是,如果它们0作为要动态分配的大小的参数传递,那么我想退出/返回该函数,但该函数本身返回 achar *所以我无法做类似的事情return -1;,我该怎么办围绕这一点,同时保留功能并执行逻辑以在那里分配内存?有办法吗?
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x == 0)
return ;
char *mem{ new char[x] };
return mem;
}
Run Code Online (Sandbox Code Playgroud)
指示指针未指向有效内存的正确方法是使用nullptr. 因此return,在内存分配失败的情况下,您的声明只是:
return nullptr;
Run Code Online (Sandbox Code Playgroud)
当然,函数的调用者nullptr在尝试取消引用之前需要确保返回的指针不是。
鉴于输入参数必须是 an ,执行此操作的规范正确方法int是:
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x <= 0)
throw std::bad_alloc();
return new char[x];
}
Run Code Online (Sandbox Code Playgroud)
或者
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x <= 0)
return nullptr;
return new(std::nothrow) char[x];
}
Run Code Online (Sandbox Code Playgroud)
取决于您是希望它抛出异常还是在出错时返回 nullptr。我建议你选择一个而不是混合它们以保持一致性
通常的做法是返回nullptr:
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x == 0)
return nullptr; // here!
char *mem{ new char[x] };
return mem;
}
Run Code Online (Sandbox Code Playgroud)