[英]Why does std::set::insert() call operator<() with bad parameter
[英]Can std::set::insert() call the assignment operator?
我有一個帶有自定義賦值運算符的類,該類故意引入了受控副作用。
如果我有這些元素的std::set
,我想知道是否可以使用insert
來調用賦值運算符。
即:
class A
{
public:
A & operator=(A const & rhs)
{
// custom assignment operator with deliberate side effects
// Could this be called with use of std::set::insert()?
}
};
std::set<A> a;
// Is it possible with this, or any use of "insert", that
// the assignment operator will ever be called?
a.insert(A());
可以使用std::set::insert
調用賦值運算符嗎?
在C ++ 11之前的版本中,理論上可以。 毫無疑問,C ++ 11禁止使用它,因為實際上沒有實現過。 在C ++ 11中, std::set
成員不必支持分配。 在C ++ 11之前的版本中,某些支持概念的實現可能具有使用賦值的代碼,以檢查您的類是否支持該賦值,但是該賦值應處於未評估的上下文中,因此實際上不會調用該運算符。
C ++ 11標准要求與std::set::insert
一起使用的類型為“ CopyInsertable”,“ MoveInsertable”或“ EmplaceConstructible”,具體取決於您使用的插入函數(23.2.3 / 4)。
例如,這定義為:
T是從args到X的EmplaceConstructible,對於args為零或多個參數,意味着以下表達式格式正確:
allocator_traits<A>::construct(m, p, args);
(23.2.1 / 13)
在這三種情況下,默認行為是std::allocator
,它使用新的位置(17.6.3.5/2):
::new((void*)c)A(forward<Args>(args)...)
根據不同的insert
的功能,在我們的情況下args
是任一類型的表達式A
,類型的右值A
或一些其他參數。 但是在所有情況下,都使用構造函數或復制構造函數,而不使用賦值運算符。
這就是標准所說的(和GCC 4.6.3一樣)。 即使沒有理由使用賦值運算符,某些編譯器仍然可以執行。 因此,我建議不要過分依賴它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.