我有一個包含 ID 和類物件的全域地圖物件,但我不明白為什么要呼叫地圖中物件的解構式。
#include <map>
#include <iostream>
#include <cassert>
#include <chrono>
#include <thread>
class TestMapObject{
private:
std::string m_sName;
public:
TestMapObject(const std::string& sName){
std::cout << "Constructor called" << std::endl;
m_sName = sName;
}
~TestMapObject(){
std::cout << "Destructor called" << std::endl;
}
const std::string& GetName(){
return m_sName;
}
};
namespace Test{
enum ETestMapKeyId{
k_ETestMapKeyNone = 0,
k_ETestMapKeyFirst,
k_ETestMapKeySecond,
};
std::map<ETestMapKeyId, TestMapObject> g_tMap;
TestMapObject* GetMapObjectById(ETestMapKeyId eID){
auto itFound = g_tMap.find(eID);
assert(itFound != g_tMap.end());
return &itFound->second;
}
}
int main(){
Test::g_tMap.insert(std::pair<Test::ETestMapKeyId,TestMapObject>(Test::k_ETestMapKeyFirst,TestMapObject("Alice")));
Test::g_tMap.insert(std::pair<Test::ETestMapKeyId,TestMapObject>(Test::k_ETestMapKeySecond,TestMapObject("Mocha")));
//destructor gets called here
std::cout << " are we destructed? " << std::endl;
TestMapObject* tmKeyFirst = Test::GetMapObjectById(Test::k_ETestMapKeyFirst);
TestMapObject* tmKeySecond = Test::GetMapObjectById(Test::k_ETestMapKeySecond);
for(;;){
std::this_thread::sleep_for (std::chrono::seconds(1));
std::cout << tmKeyFirst->GetName() << std::endl ;
std::cout << tmKeySecond->GetName() << std::endl ;
}
return 0;
}
我可以使用 GetMapObjectById 檢索指向物件的指標,并且可以連續列印它們的名稱(考慮到呼叫了它們的解構式,這可能是未定義的行為)。但我不確定為什么在應用程式結束之前呼叫解構式..
輸出
Constructor called
Destructor called
Destructor called
Constructor called
Destructor called
Destructor called
are we destructed?
---continues loop print
Alice
Mocha
uj5u.com熱心網友回復:
您看到的不是std::map被破壞,而是您用來在地圖中插入元素的臨時物件。您可以使用 emplace 來避免構建(和破壞)該臨時物件:
Test::g_tMap.emplace(Test::k_ETestMapKeyFirst,"Alice");
Test::g_tMap.emplace(Test::k_ETestMapKeySecond,"Mocha");
現場演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493785.html
標籤:C
上一篇:static_pointer_cast呼叫應該是std::限定的,還是依賴于ADL?
下一篇:C 為什么我不能拋出一個抽象類?
