本文介绍了下面的代码如何访问已删除的对象。我知道显式调用构造函数将创建临时对象,该对象将立即被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 此声明如何成功运行 obj = b [ 0 ]; cout<< obj.a<< << obj。 b<< \ n; obj = b [ 1 ]; cout<< obj.a<< << obj。 b<< \ n; // code 提前致谢 #include < vector > #include < iostream > #include conio.h 使用 命名空间标准; class B { public : int a; int b; public : B(){} B( int c, int d):a(c),b(d){cout<< contructor \ n;} ~B(){cout<< destructor \ n;} }; int main() { std :: vector< B> b; B obj; b.push_back(B( 10 , 20 )); b.push_back(B( 30 , 40 )); obj = b [ 0 ]; cout<< obj.a<< << obj。 b<< \ n; obj = b [ 1 ]; cout<< obj.a<< << obj。 b<< \ n; getch(); } 输出: contructor 析构函数 contructor 析构函数析构函数 10 20 30 40 解决方案 你的解释是错误的。调用push_back()会使堆栈对象的副本插入到向量中。 这会创建一个具有自动存储持续时间的对象: b.push_back(B( 10) , 20 )); 立即超出范围。在堆栈对象上调用析构函数,但向量中存在一个新副本。 http: //www.cplusplus.com/reference/vector/vector/ [ ^ ] How does this statement is able to run successfullyobj = b[0];cout<<obj.a<<" "<<obj.b<<"\n";obj = b[1];cout<<obj.a<<" "<<obj.b<<"\n";//codeThanks in advance#include<vector>#include<iostream>#include"conio.h"using namespace std;class B{public:int a ;int b;public:B(){}B(int c,int d):a(c),b(d){cout<<"contructor\n";}~B(){cout<<"destructor\n";}};int main(){std::vector<B> b;B obj;b.push_back(B(10,20));b.push_back(B(30,40));obj = b[0];cout<<obj.a<<" "<<obj.b<<"\n";obj = b[1];cout<<obj.a<<" "<<obj.b<<"\n";getch();}Output:contructordestructorcontructordestructordestructor10 2030 40 解决方案 Your interpretation is wrong. Calling push_back() makes a copy of the stack object to insert in the vector. This creates an object with automatic storage duration:b.push_back(B(10,20));which immediately goes out of scope. The destructor is called on the stack object but a new copy exists in the vector.http://www.cplusplus.com/reference/vector/vector/[^] 这篇关于下面的代码如何访问已删除的对象。我知道显式调用构造函数将创建临时对象,该对象将立即被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 11:58