关于C++0x右值使用中的效率问题
如下两个成员方法,结果反汇编出来的结果让我对右值的效率甚是怀疑。很明显,基于左值的比右值的效率高多了,于是,我就想问下,右值究尽该使用在何种场合?
#include <windows.h>
#include <tchar.h>
#include <iostream>
#include <string>
#ifndef tstring
#ifdef _UNICODE
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif
#endif
struct MyData
{
TCHAR szName[64];
MyData()
{
szName[0] = 0;
}
MyData( LPCTSTR pszName )
{
_tcscpy_s(szName, pszName);
}
tstring GetNameL(){ return szName; }
tstring&& GetNameR()
{
return std::move(tstring(szName));
}
};
相对应的反汇编结果(左值):tstring GetNameL(){ return szName; }
00401040 push ebp
00401041 mov ebp,esp
00401043 push ecx
00401044 xor ecx,ecx
00401046 mov dword ptr [esi+14h],7
0040104D mov dword ptr [esi+10h],0
00401054 mov word ptr [esi],cx
00401057 mov ecx,eax
00401059 push edi
0040105A mov dword ptr [ebp-4],0
00401061 lea edi,[ecx+2]
00401064 mov dx,word ptr [ecx]
00401067 add ecx,2
0040106A test dx,dx
0040106D jne MyData::GetNameL+24h (401064h)
0040106F sub ecx,edi
00401071 sar ecx,1
00401073 push ecx
00401074 mov ecx,esi
00401076 call std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >::assign (4011D0h)
0040107B mov eax,esi
0040107D pop edi
0040107E mov esp,ebp
00401080 pop ebp
00401081 ret
右值:tstring str = mydata.GetNameR();
0040106E xor esi,esi
00401070 add esp,0Ch
00401073 mov edi,7
00401078 xor ecx,ecx
0040107A lea eax,[esp+40h]
0040107E mov dword ptr [esp+1Ch],edi
00401082 mov dword ptr [esp+18h],esi
00401086 mov word ptr [esp+8],cx
0040108B lea edx,[eax+2]
0040108E mov edi,edi
00401090 mov cx,word ptr [eax]
00401093 add eax,2
00401096 cmp cx,si
00401099 jne wWinMain+50h (401090h)
0040109B sub eax,edx
0040109D sar eax,1
0040109F push eax
004010A0 lea eax,[esp+44h]
004010A4 lea ecx,[esp+0Ch]
004010A8 call std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >::assign (401260h)
004010AD cmp dword ptr [esp+1Ch],8
004010B2 jb wWinMain+82h (4010C2h)
004010B4 mov edx,dword ptr [esp+8]
004010B8 push edx
004010B9 call dword ptr [__imp_operator delete (4020ACh)]
004010BF add esp,4
004010C2 mov dword ptr [esp+1Ch],edi
004010C6 mov dword ptr [esp+18h],esi
004010CA xor eax,eax
004010CC mov dword ptr [esp+38h],edi
004010D0 mov dword ptr [esp+34h],esi
004010D4 xor ecx,ecx
004010D6 lea edi,[esp+8]
004010DA lea esi,[esp+24h]
004010DE mov word ptr [esp+8],ax
004010E3 mov word ptr [esp+24h],cx
004010E8 call std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >::assign (401140h)
[解决办法]
tstring&& GetNameR()
{
return std::move(tstring(szName));
}
明显是错的
而且你这样专门构造个临时对象去右值引用不是多此一举么?
[解决办法]
tstring&& GetNameR()
本身貌似就是一个没意义的语法。
