因此,为了更好地理解新/删除(真的用小例子向我自己证明为什么接口需要虚拟析构函数),我想了解内存泄漏,以便我可能生活在对它们的恐惧中.但是我很难接触到泄漏,可以这么说; 实际上,我也很难用new/delete.
这是我最简单的版本:
int* P1 = new int(43);
cout<<"P1 = "<<P1<<endl;
cout<<"*P1 = "<<*P1<<endl;
delete P1;
cout<<"P1 = "<<P1<<endl;
cout<<"*P1 = "<<*P1<<endl;
Run Code Online (Sandbox Code Playgroud)
这打印:
P1 = 0xcc0340
*P1 = 43
P1 = 0xcc0340
*P1 = 43
Run Code Online (Sandbox Code Playgroud)
我在课堂上有一些更复杂的东西,但是这个例子说明了我的失败.我认为删除需要一个指针并释放它的内存,从而使指针无效或至少它指向什么?我必须做一些非常简单的事情.
我有类,一个Employee类和一个BankAccount类,employee类将BankAccount类作为私有变量指针.
这就是我想要做的:
BankAccount在每个Employee值中设置所有sBankAccounts每一个Employee在函数结束.我使用成员函数setter Employee来设置BankAccount指针.BankAccount有一个私有变量,这是金额.后来我在一个指向每个BankAccount's内存地址的指针上调用delete .在我打电话给印刷品以查看每个银行的银行值之后Employee,它仍然是每个的打印值BankAccount
如果我调用delete不应该删除堆上的内存并且调用print时不输出任何内容BankAccount?
这是代码:
vector<Employee*> employees;
//get employee full name & salary and return
employees.push_back(get_employee_info());
//setup their bank account
setup_bank(employees);
//make temp pointer to store bank memory address
BankAccount * tempBankPtr;
for (int i =0; i < employees.size(); i++) {
tempBankPtr =employees[i]->get_bank();
delete tempBankPtr // delete the heap object …Run Code Online (Sandbox Code Playgroud) 我最近开始学习 C++ 中的智能指针和移动语义。但我不明白为什么这段代码有效。我有这样的代码:
#include <iostream>
#include <memory>
using namespace std;
class Test
{
public:
Test()
{
cout << "Object created" << endl;
}
void testMethod()
{
cout << "Object existing" << endl;
}
~Test()
{
cout << "Object destroyed" << endl;
}
};
int main(int argc, char *argv[])
{
Test* testPtr = new Test{};
{
unique_ptr<Test> testSmartPtr(testPtr);
}
testPtr->testMethod();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的输出是:
Object created
Object destroyed
Object existing
Run Code Online (Sandbox Code Playgroud)
为什么行testPtr->testMethod()有效?如果指针是左值,unique_ptr 不会在销毁时删除分配给它的指针吗?
编辑:我从评论中了解到,此方法不会检查指针是否存在。如果是这样,有没有办法检查指针是否有效?
编辑:我了解到我不应该对无效指针做任何事情。感谢您的所有回答和评论。
编辑:即使这个代码也有效:
#include <iostream>
#include <memory> …Run Code Online (Sandbox Code Playgroud)