編程語言中的大多數事情並不完全和完全免費的。除非你編寫僅編譯時代碼,否則編寫身份函數不太可能是免費的。
讓我們返工你的代碼位:
#include <algorithm>
#include <iostream>
template <typename T>
T id1(T&& t)
{
return t;
}
template <typename T>
T id2(T&& t)
{
return std::move(t);
}
class X
{
public:
X()
{ output0("Xdef"); }
X(std::string const& s) : label_(s)
{ output1("Xstr",s); }
X(X const& x) : label_(x.label_)
{ output1("Xcopy", x); }
X(X&& x) : label_(std::move(x.label_))
{ output1("Xmove", x); }
X& operator =(X const& x)
{
output1("operator =copy", x);
label_ = x.label_;
return *this;
}
X& operator =(X&& x)
{
using std::swap;
output1("operator =move", x);
swap(label_, x.label_);
return *this;
}
~X()
{ output0("~X"); }
private:
void output_id() const
{
std::cout << this << '[' << label_ << "]";
}
void output0(std::string const& name) const
{
output_id();
std::cout << ": " << name << "()" << std::endl;
}
void output1(std::string const& name, std::string const& str) const
{
output_id();
std::cout
<< ": " << name
<< "(\"" << str
<< "\")" << std::endl;
}
void output1(std::string const& name, X const& arg) const
{
output_id();
std::cout << ": " << name << '(';
arg.output_id();
std::cout << ')' << std::endl;
}
std::string label_;
};
int main()
{
{
std::cout << "CASE A:\n";
auto x = X("x1");
}
std::cout << "\n";
{
std::cout << "CASE B:\n";
auto x = id1(X("x2"));
}
std::cout << "\n";
{
std::cout << "CASE C:\n";
auto x = id2(X("x3"));
}
std::cout << "\n";
{
std::cout << "CASE D:\n";
X x = id1(X("x4"));
}
std::cout << "\n";
{
std::cout << "CASE E:\n";
X x = id2(X("x5"));
}
}
並運行時,它輸出(使用GCC V4.8快照):
$ ./a.out
CASE A:
0x7fff411fc530[x1]: Xstr("x1")
0x7fff411fc530[x1]: ~X()
CASE B:
0x7fff411fc540[x2]: Xstr("x2")
0x7fff411fc520[x2]: Xcopy(0x7fff411fc540[x2])
0x7fff411fc540[x2]: ~X()
0x7fff411fc520[x2]: ~X()
CASE C:
0x7fff411fc540[x3]: Xstr("x3")
0x7fff411fc520[x3]: Xmove(0x7fff411fc540[])
0x7fff411fc540[]: ~X()
0x7fff411fc520[x3]: ~X()
CASE D:
0x7fff411fc540[x4]: Xstr("x4")
0x7fff411fc520[x4]: Xcopy(0x7fff411fc540[x4])
0x7fff411fc540[x4]: ~X()
0x7fff411fc520[x4]: ~X()
CASE E:
0x7fff411fc540[x5]: Xstr("x5")
0x7fff411fc520[x5]: Xmove(0x7fff411fc540[])
0x7fff411fc540[]: ~X()
0x7fff411fc520[x5]: ~X()
$
情況A只是調用構造函數對於X. =
在這種情況下相當於將=
的右側傳遞給X,即它不是一個賦值。
情況B調用id1()
它不移動它的返回參數。由於返回的值沒有在id()的調用堆棧上定義,並且該值是一個左值(包含右值),所以它不會在返回時自動移動並因此被複制。
情況C調用id2()
,它在返回時調用移動構造函數。
病例D和E分別與病例B和病例C相同,只是如果您對此持懷疑態度,則不會使用auto
。
在最壞的情況下,移動應該被看作是優化的副本,並且與副本一樣糟糕(儘管它們往往會好得多)。即使是最佳的移動也會有成本(例如,將一些數據(通常)從一個堆棧幀複製到另一個堆棧幀)。在運行時代碼中完全避免複製/移動的唯一方法是返回值優化和複製ellison符合編譯器使用的條件。
問題是函數聲明並不傳達返回的引用是否仍然引用傳遞給它的同一個對象。強制編譯器檢查函數的實現是不合理的,以便確定它返回的是什麼,並使臨時的生命週期取決於此分析。 – sellibitze