![](/img/trans.png)
[英]Why does compiler use move constructor instead of the copy constructor
[英]Why does this call the copy constructor, not the move constructor?
我有一個類, PlayerInputComponent
:
。H:
class PlayerInputComponent
{
public:
PlayerInputComponent(PlayerMoveComponent& parentMoveComponent_, std::unique_ptr<IRawInputConverter> inputConverter_);
PlayerInputComponent(PlayerInputComponent&& moveFrom);
void update();
private:
std::unique_ptr<IRawInputConverter> inputConverter;
PlayerMoveComponent& parentMoveComponent;
};
}
的.cpp:
PlayerInputComponent::PlayerInputComponent(PlayerMoveComponent& parentMoveComponent_, std::unique_ptr<IRawInputConverter> inputConverter_) :
parentMoveComponent(parentMoveComponent_),
inputConverter(std::move(inputConverter_))
{
}
PlayerInputComponent::PlayerInputComponent(PlayerInputComponent&& moveFrom) :
parentMoveComponent(moveFrom.parentMoveComponent),
inputConverter(moveFrom.inputConverter.release())
{
}
和一個類PlayerMoveComponen
t,它包含一個PlayerInputComponent
成員,並使用作為參數傳遞的std::unique_ptr
對其進行初始化。 它的構造函數:
PlayerMoveComponent::PlayerMoveComponent(/* other parameters */ std::unique_ptr<IRawInputConverter> inputConverter) :
//other initializations
inputComponent(PlayerInputComponent(*this, std::move(inputConverter)))
{
}
我為PlayerInputComponent
類定義了自己的移動構造函數,因為我的理解是不會為包含引用成員的類構造默認移動構造函數。 在這種情況下,雖然我知道引用將保留在PlayerInputComponent
對象的生存期的持續時間范圍內。
由於我是從臨時初始化PlayerMoveComponent
的inputComponent
變量,我相信應該發生以下兩件事之一:
PlayerInputComponent
的移動構造函數用於初始化playerInputComponent
成員變量。 但是,Visual Studio 2012吐出了這個:
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
1> with
1> [
1> _Ty=SDLGame::IRawInputConverter
1> ]
1> c:\program files\microsoft visual studio 11.0\vc\include\memory(1447) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
1> with
1> [
1> _Ty=SDLGame::IRawInputConverter
1> ]
1> This diagnostic occurred in the compiler generated function 'PlayerInputComponent::PlayerInputComponent(const PlayerInputComponent &)'
為什么在這里調用復制構造函數? 使PlayerInputComponent
類的parentMoveComponent
成員成為一個常規的ParentMoveComponent
實例,而不是一個引用,擺脫了錯誤,但我不明白為什么 - 我已經測試並驗證,只要你提供你的參考成員就可以移動構建對象自己的移動構造函數,那么交易是什么?
如果這不能真正回答你的問題,我很抱歉,我只是想對你問題的明顯復雜性做出反應。 如果可以的話,這不會簡單一千倍:
/******************** ********** ********************/
class C {};
class B;
class A
{
public:
A(): _b(nullptr), _c(nullptr) {}
A( B *b, C *c ): _b(b), _c(c) {}
A( A&& a ): _b(a._b), _c(a._c) {}
private:
C *_c;
B *_b;
};
class B
{
public:
B( /* other parameters */ C *c ): _a( A(this,c) ) {}
private:
A _a;
};
/******************** ********** ********************/
int main()
{
C c;
B b(&c);
}
並實現同樣的目標? 我沒有反對使用c ++ 11中的新功能,比如std::unique_ptr
,但恕我直言,確保指針永遠不能從兩個地方取消引用不應該是運行時檢查的問題(除非非常罕見)案例),但設計問題..不應該嗎?
如果使用=
初始化新Object,則默認情況下將觸發復制構造函數。 要觸發移動構造函數,您需要更改operator=
的行為。您可以在此處找到示例希望我幫助過您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.