我有三個問題:在函數f的範圍分配關於移動構造函數
A ::海峽的記憶。將它移動到全局var vec中的元素後,當f的範圍超出時,內存塊是否仍然安全?
對於結構B,沒有明確給出移動構造函數,是否有像結構A那樣的默認構造函數?
struct A
{
A(const char* p):str(p){}
A(const A&& a) : str(std::move(a.str))
{
}
string str;
};
struct B
{
B(const char* p):str(p){}
string str;
};
vector<A>vec;
void f()
{
vec.emplace_back(A("hello")); //in vc2010 it will invoke emplace_back(T&&)
}
int _tmain(int argc, _TCHAR* argv[])
{
f();
const char* p = vec[0].str.c_str();
cout << p << endl;
return 0;
}
3.And我可以證實這種危險情況,STL容器永遠不會發生?
struct String
{
char* pStr; //allocate on heap
int* someptr; //if point to allocate on stack
size_t len;
String (const String&& s)
{
// something like this:
pStr = s.pStr; //ok,safe
len = s.len;
s.pStr = nullptr;
someptr = s.someptr; //danger
}
};