9
我做從℃的運動++入門第五版,它是這樣:在你的 字符串類的移動操作將打印語句並重新運行程序從練習13.48:爲什麼不移動構造函數?
練習13.50即所使用的矢量看避免了副本時,在§13.6.1(第 534)。(P.544)
String
的是用於實踐的一類,它們的行爲像std::string
沒有使用任何模板。該String.h
文件:
class String
{
public:
//! default constructor
String();
//! constructor taking C-style string i.e. a char array terminated with'\0'.
explicit String(const char * const c);
//! copy constructor
explicit String(const String& s);
//! move constructor
String(String&& s) noexcept;
//! operator =
String& operator = (const String& rhs);
//! move operator =
String& operator = (String&& rhs) noexcept;
//! destructor
~String();
//! members
char* begin() const { return elements; }
char* end() const { return first_free; }
std::size_t size() const {return first_free - elements; }
std::size_t capacity() const {return cap - elements; }
private:
//! data members
char* elements;
char* first_free;
char* cap;
std::allocator<char> alloc;
//! utillities for big 3
void free();
};
執行情況默認情況下,複製和移動String.cpp
構造:
//! default constructor
String::String():
elements (nullptr),
first_free (nullptr),
cap (nullptr)
{}
//! copy constructor
String::String(const String &s)
{
char* newData = alloc.allocate(s.size());
std::uninitialized_copy(s.begin(), s.end(), newData);
elements = newData;
cap = first_free = newData + s.size();
std::cout << "Copy constructing......\n";
}
//! move constructor
String::String(String &&s) noexcept :
elements(s.elements), first_free(s.first_free), cap(s.cap)
{
s.elements = s.first_free = s.cap = nullptr;
std::cout << "Move constructing......\n";
}
Main.cpp
:
int main()
{
std::vector<String> v;
String s;
for (unsigned i = 0; i != 4; ++i)
v.push_back(s);
return 0;
}
輸出:
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
可以看出,移動構造函數根本沒有被調用。當向量分配更多內存時,爲什麼不調用移動構造函數?
更新:
編譯器的信息:
gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)
main.cpp
與印刷能力和輸出中:
int main()
{
std::vector<String> v;
String s;
for (unsigned i = 0; i != 4; ++i)
{
std::cout << v.capacity() << "\n";
v.push_back(s);
}
return 0;
}
輸出:
0
Copy constructing......
1
Copy constructing......
Copy constructing......
2
Copy constructing......
Copy constructing......
Copy constructing......
4
Copy constructing......
[對我的作品(http://ideone.com/9YaaZ0),一旦我添加足夠的缺失定義來編譯。你正在使用哪種編譯器?檢查矢量的容量 - 可能它預留了四個或更多元素的空間? –
這是哪個編譯器?在gcc中工作(4.7.2和4.8.2 - 只有我現在可以訪問的那些...) – Nim
@MikeSeymour 4.73我更新了線程,增加了打印容量。 –