我收到了一個來自gcc的奇怪錯誤,無法找出原因。我做了下面的示例代碼來使問題更清楚。基本上,定義了一個類,爲此我使其複製構造函數和複製賦值運算符爲私有,以防止意外調用它們。vector :: push_back堅持使用複製構造函數雖然提供了移動構造函數
#include <vector>
#include <cstdio>
using std::vector;
class branch
{
public:
int th;
private:
branch(const branch& other);
const branch& operator=(const branch& other);
public:
branch() : th(0) {}
branch(branch&& other)
{
printf("called! other.th=%d\n", other.th);
}
const branch& operator=(branch&& other)
{
printf("called! other.th=%d\n", other.th);
return (*this);
}
};
int main()
{
vector<branch> v;
branch a;
v.push_back(std::move(a));
return 0;
}
我希望這段代碼能夠編譯,但是它會失敗,並且會導致gcc失敗。其實gcc抱怨 「分支::分支(常規分支&)是私人的」,據我所知不應該被稱爲。
賦值運算符的工作,因爲如果我
branch a;
branch b;
b = a;
更換主車身(),它會編譯和運行符合預期。
這是gcc的正確行爲嗎?如果是這樣,上面的代碼有什麼問題? 任何建議對我都有幫助。謝謝!
適用於gcc-4.6.1。 – 2012-07-15 01:15:08
我正在使用gcc 4.7.1-2。我會嘗試4.6.1。謝謝! – BreakDS 2012-07-15 02:25:01
通過閱讀N3242,應該允許此代碼(但如果移動構造函數確實會拋出異常,則該程序具有未定義行爲)。 – aschepler 2012-07-15 13:41:18