我正在使用emplace_back
將項目添加到std::deque
。在施工期間,新物品可能會將其他物品添加到正在構建的std::deque
中。這導致非常有趣的行爲。考慮這個片斷:在調用emplace_back期間修改std :: deque是否合法?
#include <iostream>
#include <deque>
#include <string>
struct foo
{
std::string m_marker;
foo(std::deque<foo>& into, const std::string& marker, bool createInner = true)
: m_marker(marker)
{
if (createInner)
{
std::cout << "Marker is " << m_marker << std::endl;
into.emplace_back(into, "my other marker", false);
std::cout << "Marker is now " << m_marker << std::endl;
}
}
};
int main()
{
std::deque<foo> foos;
foos.emplace_back(foos, "my initial marker");
std::cout << "There are " << foos.size() << " items in the deque:" << std::endl;
for (foo& f : foos)
{
std::cout << f.m_marker << std::endl;
}
}
它創建foo
的deque
對象。第一個對象的標記是"my initial marker"
,並且由於createInner
是true
,它將創建第二個對象。我希望以下結果:
Marker is my initial marker
Marker is now my initial marker
There are 2 items in the deque:
my initial marker
my other marker
然而,隨着鏗鏘++(標籤/蘋果/鐺-421.11.66))和libc(++(不知道它是什麼版本),這是我得到:
Marker is my initial marker
Marker is now my other marker
There are 2 items in the deque:
my other marker
正如您所看到的,第一個對象的m_marker
字段被第二個對象覆蓋,而第二個顯示在雙側的對象現在是空的。所以很明顯,某處存在一個錯誤,它必須是在調用emplace_back
期間修改deque
的未定義行爲,或者libC++沒有完成其工作。哪一個?
_why_你會那麼做嗎?! – stefan
您可能感興趣的相關問題:http://stackoverflow.com/questions/16616253/is-vectorinsert-allowed-to-reserve-only-once-and-avoid-further-capacity-checks –
我會說這是未定義的行爲。該標準僅爲函數運行前後提供了保證。 –