#include <iostream>
#include <memory>
#include <unordered_map>
#include <memory>
#include <vector>
#include <list>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;
class Word {
public:
Word() {
cout << "Word!!!" << endl;
doc = "abcd";
}
~Word() {
cout << "~word!!!" << endl;
}
string ToString() {
return doc;
}
private:
string doc;
};
class Hit {
public:
Hit() {
cout << "Hit!!!" << endl;
}
~Hit() {
cout << "~Hit!!!" << endl;
}
Word GetWord() {
return this->word;
}
private:
Word word;
};
void print(const string& str) {
cout << str << endl;
}
int main()
{
{
Hit hit;
const string& str = hit.GetWord().ToString();
cout << "------------------" << endl;
print(str);
}
return 0;
}
输出:
Word!!!
Hit!!!
~word!!!
------------------
abcd
~Hit!!!
~word!!!
原因在于hit.GetWord()返回一个临时对象,返回之后就析构了,调用了ToString获取其中的变量。