c++ - 为什么在构造函数中将字符串分配给指针是安全的?
问题描述
我有一堂课:.h
class test {
public:
int Length;
char* Name;
int* ARR;
test(int l, char* n, int* a);
test();
};
.cpp
test::test(int l, char* n, int* a){
Length=l;
Name=n;
ARR=a;
}
和 main.cpp
#include<iostream>
void InAFunc(test *kio) {
int foo[3] = { 1,2,3 };
*kio = test(7, "Hello!", foo);
}
int main() {
test mmk;
InAFunc(&mmk);
std::cout << mmk.Name << mmk.ARR[1];
}
据我所知,我可能会在 ARR 上遇到异常,因为变量 foo 已在函数 InAFunc 的末尾释放。我需要对 Arr 执行 new 或 malloc 以避免它。我的问题是为什么“你好!” 是安全的?我过去写过很多这样的代码,但从来没有错。为什么在没有 new 或 malloc 的构造函数中留下一个字符串是可以的?这个类中的变量名是一个指针。
解决方案
字符串“Hello”是在string literal
整个程序期间都存在的。因此,您始终可以在不破坏指针的情况下指向它。它不会在函数结束时被销毁。
推荐阅读
- reactjs - 如何在 django rest 框架中播放上传的视频
- python - 删除 OpenCV 中未使用的形状
- cmake - 父 CMAKE_SOURCE_DIR 的 FetchContent 问题
- aws-api-gateway - 无服务器:从 SecretsManager 值创建 api 密钥
- r - 如何根据前一列的名称重命名列
- python - 加载torchtext模型+词汇进行推理的正确方法
- python - 最大最小流量算法
- python - 更新的代码 - 如何使用 xlsxwriter 将所有值放在 Python 中的列中
- dropzone - 多次上传时的 Dropzone 加载问题
- javascript - node/js es6“类”从函数继承原型(链)