测试新的移动语义。
我刚刚询问了我在使用移动构造函数时遇到的问题。但正如评论中所表明的那样,问题实际上是当您使用标准的“复制和交换”习惯用法时,“移动赋值”运算符和“标准赋值”运算符发生冲突。
这是我正在使用的类:
#include <string.h>
#include <utility>
class String
{
int len;
char* data;
public:
// Default constructor
// In Terms of C-String constructor
String()
: String("")
{}
// Normal constructor that takes a C-String
String(char const* cString)
: len(strlen(cString))
, data(new char[len+1]()) // Allocate and zero memory
{
memcpy(data, cString, len);
}
// Standard Rule of three
String(String const& cpy)
: len(cpy.len)
, data(new char[len+1]())
{
memcpy(data, cpy.data, len);
}
String& operator=(String rhs)
{
rhs.swap(*this);
return *this;
}
~String()
{
delete [] data;
}
// Standard Swap to facilitate rule of three
void swap(String& other) throw ()
{
std::swap(len, other.len);
std::swap(data, other.data);
}
// New Stuff
// Move Operators
String(String&& rhs) throw()
: len(0)
, data(null)
{
rhs.swap(*this);
}
String& operator=(String&& rhs) throw()
{
rhs.swap(*this);
return *this;
}
};
我认为相当沼泽标准。
然后我像这样测试了我的代码:
int main()
{
String a("Hi");
a = String("Test Move Assignment");
}
这里的任务是a
应使用“移动分配”运算符。但是与“标准分配”运算符(被编写为标准复制和交换)有冲突。
> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix
> g++ -std=c++11 String.cpp
String.cpp:64:9: error: use of overloaded operator '=' is ambiguous (with operand types 'String' and 'String')
a = String("Test Move Assignment");
~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String.cpp:32:17: note: candidate function
String& operator=(String rhs)
^
String.cpp:54:17: note: candidate function
String& operator=(String&& rhs)
^
现在我可以通过将“标准分配”运算符修改为:
String& operator=(String const& rhs)
{
String copy(rhs);
copy.swap(*this);
return *this;
}
但这并不好,因为它会影响编译器优化复制和交换的能力。请参阅什么是复制和交换习惯用法?here https://stackoverflow.com/a/3279550/14065 and here https://stackoverflow.com/a/3279616/14065
我是否遗漏了一些不那么明显的东西?