c++ - 一次又一次地获得相同的内存

标签 c++ vector

在我的程序中,我在一个循环中创建一个类的对象并将其存储在一个 vector 中。然后我打印对象的地址和成员变量。之后我擦掉它们。我看到每次我看到分配给我的对象的相同地址和作为指针的成员变量时。谁能解释这种行为。

#include <iostream>
#include <vector>

using namespace std;

typedef struct csock {
unsigned int _refCount;
mutable pthread_mutex_t _pdata_mutex;
pthread_attr_t attr;
bool _bSocketClosed;            /// used for testing while closing the socket
int _iSockFD;                   /// Holds the native socket descriptor
void* _pfnArgs; 
void* _logger;                  /// For debug logging
bool _isServiceRunning; 
pthread_t _thread_id;           /// Thread id for the listener service
int _pipes[2];                  /// For stop signal communication
pthread_mutex_t* _countMutex;
unsigned long  _idleTimeOut;                //Idle Time Out
FILE* fp;
} __attribute__((packed)) csock_t;




class csocket
{
protected:
void* _pImpl;

public :

csocket(){
csock_t* ps = new csock_t;
this->_pImpl = reinterpret_cast<void*> (ps);
std::cout<<"\n ps is "<<ps <<" _pImpl is "<<_pImpl <<endl;
}
void* getImpl()
{
    return _pImpl;
}
};


int main ()
{

vector<csocket> v;

 for (int i=0; i< 5; ++i) {
    v.push_back(csocket());
    cout<<"\n after pushback "<<v[v.size()-1].getImpl();
    cout<<"\n after pushback object is"<<&(v[v.size()-1]);
    delete (csock_t*) v[0].getImpl();
    v.erase(v.begin()+0);
}
cout <<"\n size of vector is "<<v.size();
return 0;
}

我正在我的系统中添加输出

ps is 0x8368008 _pImpl is 0x8368008
after pushback 0x8368008
after pushback object is0x8368078

ps is 0x8368008 _pImpl is 0x8368008
after pushback 0x8368008
after pushback object is0x8368078

ps is 0x8368008 _pImpl is 0x8368008
after pushback 0x8368008
after pushback object is0x8368078

ps is 0x8368008 _pImpl is 0x8368008
after pushback 0x8368008
after pushback object is0x8368078

ps is 0x8368008 _pImpl is 0x8368008
after pushback 0x8368008
after pushback object is0x8368078

最佳答案

在您删除 对象之后,它之前占用的内存被标记为空闲,并且它的所有权被传递给堆,因此允许堆重用它占用的空间用于 future 的分配。所以恰好堆重用了完全相同的内存块。

关于c++ - 一次又一次地获得相同的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3466799/

相关文章:

vector - 在向量中交换两个元素的惯用方式是什么

r - 获取向量中矩阵索引的列名和行名

c++ - std::vector 元素的破坏顺序

sorting - 如何根据 haskell 中另一个向量的排序顺序对向量值进行重新排序?

c++ - 在 C++ 中返回对象

return 语句中的 C++11 显式转换运算符/构造函数

c++ - 大的负整数文字

string - 将i8的向量转换为Rust中u8的向量? [复制]

c++ - 为什么 GCD 会增加执行时间?

C++ 类方法继承