[英]C++ - Determine if const char* points to string literal or dynamic object
void delete_str(const char* theString) {
// if (theString is pointing to dynamic objects delete it)
delete[] theString;
// else do nothing
}
int main() {
char str[4] = {'a', 'b', 'c', '\0'};
const char* str0 = "abc"; // assign "abc" to str0
char* str1 = new char[strlen("abc")+1]; for (int i = 0; i < 4; i++) str1[i] = str[i]; // assign "abc" to str1
delete_str(str0); // run time error
delete_str(str1); // ok
}
In this example, I'd like to define a function delete_str()
to delete what theString
is pointing to.在这个例子中,我想定义一个函数
delete_str()
来删除theString
指向的内容。 But how could I determine if it points to a string literal or not?但是我如何确定它是否指向字符串文字?
You cannot determine that.你无法确定。 The programmer needs to manually keep track of how objects that a pointer points to were created.
程序员需要手动跟踪指针指向的对象是如何创建的。
That is one of the reasons raw pointers created from new
should not be used directly, except in the implementation of a class specifically managing a single such allocation.这就是不应直接使用从
new
创建的原始指针的原因之一,除非在专门管理单个此类分配的类的实现中。
Use std::string
.使用
std::string
。 You can obtain a null-terminated C string from a std::string
using its .c_str()
or .data()
member functions.您可以使用其
.c_str()
或.data()
成员函数从std::string
获取以空字符结尾的 C 字符串。
Only use raw pointers as non-owning pointers.仅使用原始指针作为非拥有指针。 Then you will never have to decide whether you need to
delete
it or not.那么您将永远不必决定是否需要
delete
它。 There are smart pointer such as std::unique_ptr
and containers such as std::vector
in addition to the std::string
class, all of which will handle ownership and correct delete
of non-array and array objects for you automatically.除了
std::string
类之外,还有诸如std::unique_ptr
类的智能指针和诸如std::vector
类的容器,所有这些都将自动为您处理所有权并正确delete
非数组和数组对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.