Created
April 12, 2018 23:39
-
-
Save cztchoice/0a6ea70e28c34655349fccbde575a47d to your computer and use it in GitHub Desktop.
返回stack上变量的const ref
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
#include <vector> | |
#include <string> | |
using namespace std; | |
class TestVector | |
{ | |
public: | |
~TestVector() | |
{ | |
cout << "Destruct TestVector" << endl; | |
} | |
void push_back(const string& str) | |
{ | |
m_vector.push_back(str); | |
} | |
int size() const | |
{ | |
cout << "m_vector location: " << (size_t)(&m_vector) << endl; | |
return m_vector.size(); | |
} | |
private: | |
vector<string> m_vector; | |
}; | |
const vector<string>& func() | |
{ | |
vector<string> result = {"test"}; | |
return result; | |
} | |
const vector<string>& func_return() | |
{ | |
return vector<string>{"test"}; | |
} | |
const TestVector& func_class() | |
{ | |
TestVector test; | |
test.push_back("test"); | |
cout << "func_class size in func " << test.size() << endl; | |
return test; | |
} | |
const string& func_str() | |
{ | |
string result("test"); | |
return result; | |
} | |
int main() | |
{ | |
const auto& result = func(); | |
cout << result.size() << endl; | |
const auto& result_return = func_return(); | |
cout << result_return.size() << endl; | |
auto result_str = func_str(); | |
cout << result_str << endl; | |
const auto& resultClass = func_class(); | |
cout << resultClass.size() << endl; | |
// 被析构的vector,如果调用它的成员函数是什么的结果? | |
auto testVector = new vector<string>{"test"}; | |
cout << testVector->size() << endl; // 输出1 | |
delete testVector; | |
cout << testVector->size() << endl; // 输出0 | |
/* | |
所以这个最终表现的结果是,我调用了一个dangle的vector返回的结果 | |
两步: | |
1. 返回的变量已经被析构 | |
2. 我调用已经析构变量的成员函数 | |
*/ | |
// const vector<string>& testConstRef; | |
// cout << testConstRef.size() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment