我一直在阅读智能指针,最近在课堂上我的TA说我们永远不应该使用原始指针.现在,我已经在网上做了很多阅读,并在这个网站上查看了不同的问题,但我仍然对智能指针的某些方面感到困惑.我的问题是:如果我希望在我的程序中使用它,我会使用哪个智能指针?我会展示一些代码.
所以我有一个基本的Application类,它从类AI中声明对象的声明.注意:出于测试原因,我有两个不同的智能指针,一个是唯一的,另一个是共享的.
// Application class in Application.h
class Application
{
public:
Application(){}
~Application(){}
//... additional non-important variables and such
unique_ptr<AI> *u_AI; // AI object using a unique pointer
shared_ptr<AI> *s_AI; // AI object using a shared pointer
//... additional non-important variables and such
void init();
void update();
};
// AI class in AI.h
class AI
{
public:
AI(){}
~AI(){}
bool isGoingFirst;
};
Run Code Online (Sandbox Code Playgroud)
在Application init函数中,我想创建AI对象,然后我想在更新函数中使用它.我不确定我是否正确地声明我的指针,但我知道它编译的事实,它适用于在init函数中分配和打印数据.更多代码如下.
void Application::init()
{
//.. other initialization's.
std::shared_ptr<AI> temp(new AI());
sh_AI = &temp;
sh_AI->isGoingFirst = true;
//.. …Run Code Online (Sandbox Code Playgroud) 正如标题所暗示的那样,在函数中声明非指针变量是否会导致内存泄漏?我在互联网上看了一遍,我找到了一个答案,但它是针对C而我不确定是否将同样的规则应用于C++.我目前正在改进我的旧项目,我正在努力提高内存效率.作为一个例子,我有一个加载函数,在启动期间将被调用至少10-20次,我想知道在内存上声明非指针变量会产生什么影响.
void ObjectLoaderManager::loadObject(char FileName[20])
{
char file[100] = "Resources\Models\"; // Declare object file path
strncat_s (File, FileName, 20); // Combine the file path with the input name
std::string newName; // Declare a new scring
newFile = File; // Assign File to the string newFile
int health = 10;
// Assign newFile as the name of the newly created object and assign health variable
// in later parts of the function
}
Run Code Online (Sandbox Code Playgroud)
虽然我确实理解这个函数的部分是明显坏的,而且其中很多都不是我不会做的实践,但是,我很想知道在本地化函数中反复声明非指针变量会产生什么影响.谢谢.这是我在帖子开头提到的文章的链接http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html