定义c-string的位置
Define where placed the c-string
我如何定义我需要调用"delete[]"指针或不在我的类的析构函数?指针(成员变量)可以在不同的时间指向在堆中分配或不分配的缓冲区(它可以是只读内存中的文字或堆栈中的文字)。最好的解决办法是什么?我是否需要为它使用另一个标志,或者可能是获取堆边界的地址并检查它们之间的缓冲区地址?还是有更理性的方式?
仅仅通过查看指针就无法判断指针是在自动存储库中、静态内存中还是动态内存中。在设置指针时需要存储一个标志,例如:
class classWithDynamicData {
private:
bool needToDelete;
char strData[];
public:
classWithDynamicData(int size) : needToDelete(true), strData(new char[size]) {
}
classWithDynamicData(char* data) : needToDelete(false), strData(data) {
}
~classWithDynamicData() {
if (needToDelete) delete[] strData;
}
...
// You need to define a copy constructor and an assignment operator
// to avoid violating the rule of three
};
- 不要使用动态分配的数据成员(使用
std::string
代替char *
或std::vector
代替动态分配的数据成员)或 - 使用智能指针
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- cppcheck在const std::string[]上引发警告
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 将std::string传递给WriteConsole API
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 访问 std::string 中的元素,其中字符串的位置大于其大小
- 如何使用regex_token_iterator<std::string::iterator>通过迭代器本身获取子匹配的原始字符串的位置?
- C 寻求一个std :: string :: iterator的位置
- 我可以读取向量<string>::迭代器的数字位置吗?
- 如何从字符串位置构造CSTRING/STD :: String
- C++:写入 std::string 中的特定索引位置
- 在c++ 11中,返回指向std::string中某个位置的引用/指针的最高效方法是什么?
- 定义c-string的位置
- 在指定位置复制char*到std::string,不分配新对象
- unordered_map<字符串,矢量<string>> - 当事物push_back时,内存位置会发生变化
- 使用 string.find() 确定第 i 个"str"的位置
- 如何迭代std::string中所有匹配的正则表达式,使其在c++11 std::regex中的起始位置