私は次のコードを持っていますが、私が最も気になることがいくつかあります。
#include <iostream>
#include <functional>
class Samp {
char str[10] = "Default";
public:
Samp(char s[]) { strcpy(str, s); printf("Constructor\n"); }
Samp(const Samp& s) { printf("Copy Constructor\n"); }
~Samp() { printf("Destructor\n"); }
char* out() {
return str;
}
friend std::ostream& operator<<(std::ostream& stream, const Samp& s) {
stream << s.str;
return stream;
}
};
void output(Samp s) {
std::cout << s << std::endl;
}
int main(int argc, const char * argv[]) {
std::function<void(Samp s)> o;
o = output;
o((char*)"Hello");
return 0;
}
実行時に、プログラムは次の出力を提供します
Constructor
Copy Constructor
Default
Destructor
Destructor
Program ended with exit code: 0
std::function
呼び出しへの引数は、オブジェクト内に格納されている呼び出し可能オブジェクトに完全に転送されることによって渡されstd::function
ます。
したがって、の動作はo(args...)
と同じではありませんoutput(args...)
。代わりに、次と同じです。
output( std::forward<Args...>(args...) );
またはこの具体的な例では、
output( std::forward<Samp>( (char *)"Hello" ) );
この例では、このコードの動作がとわずかに異なるため、「完全な」転送はそれほど完全ではないことがわかりoutput( (char *)"Hello" );
ます。
選択したオーバーロードの署名forward
はSamp&& forward(Samp&& arg);
です。したがって、arg
への関数呼び出しのためにバインドするための一時的なマテリアライズが必要std::forward
です。それがあなたが見る「コンストラクター」です。
次に、「コピーコンストラクタ」はoutput
、の戻り値からの関数のパラメータの初期化ですstd::forward
。Samp
移動コンストラクターがあれば、それは移動操作である可能性があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加