我有以下小班:
/// RAII wrapper for a Lua reference
class reference
{
public:
/// Construct empty reference
reference() : m_L(NULL), m_ref(LUA_NOREF) {}
/// Construct reference from Lua stack
reference(lua_State* L, int i = -1) : m_L(L) {
lua_pushvalue(L, i);
m_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
/// Destructor
~reference() {
if (m_L) luaL_unref(m_L, LUA_REGISTRYINDEX, m_ref);
}
/// Copy constructor
reference(const reference& r) : m_L(r.m_L) {
r.push();
m_ref = luaL_ref(m_L, LUA_REGISTRYINDEX);
}
/// Move constructor
reference(reference&& r) : m_L(r.m_L), m_ref(r.m_ref) {
r.m_L = NULL; // make sure r's destructor is NOP
}
/// Assignment operator
reference& operator=(reference r) {
swap(r, *this);
return *this;
}
/// Swap with other reference
friend void swap(reference& a, reference& b)
{
std::swap(a.m_L, b.m_L);
std::swap(a.m_ref, b.m_ref);
}
void push() const { lua_rawgeti(m_L, LUA_REGISTRYINDEX, m_ref); }
private:
lua_State* m_L;
int m_ref;
};
请注意,赋值运算符是使用复制和交换习语实现的,如果与右值一起使用,则应该调用移动构造函数。
但是,reference r; r = reference(L);
在输入赋值运算符之前调用复制构造函数。为什么,哦,为什么?
编写两个赋值运算符有助于:
/// Assignment operator
reference& operator=(const reference& r) {
reference copy(r);
swap(copy, *this);
return *this;
}
/// Move assignment operator
reference& operator=(reference&& r) {
swap(r, *this);
return *this;
}
但是,以禁用复制省略为代价。
值传递不应该按预期在这里工作吗?还是我的编译器(Mac 上的 Clang)坏了?
更新:
以下小测试用例可以正常工作:
#include <iostream>
using namespace std;
struct resource
{
resource(int i=1) : i(i) { print(); }
~resource() { print(); i = 0; }
void print() const
{
cout << hex << " " << uint16_t(uintptr_t(this)) << ") " << dec;
}
int i;
};
resource* alloc_res()
{
cout << " (alloc_res";
return new resource(0);
}
resource* copy_res(resource* r)
{
cout << " (copy_res";
return new resource(r->i);
}
void free_res(resource* r)
{
if (r) cout << " (free_res";
delete r;
}
struct Test
{
void print() const
{
cout << hex << " [&=" << uint16_t(uintptr_t(this))
<< ", r=" << uint16_t(uintptr_t(r)) << "] " << dec;
}
explicit Test(int j = 0) : r(j ? alloc_res() : NULL) {
cout << "constructor"; print();
cout << endl;
}
Test(Test&& t) : r(t.r) {
cout << "move"; print(); cout << "from"; t.print();
t.r = nullptr;
cout << endl;
}
Test(const Test& t) : r(t.r ? copy_res(t.r) : nullptr) {
cout << "copy"; print(); cout << "from"; t.print();
cout << endl;
}
Test& operator=(Test t) {
cout << "assignment"; print(); cout << "from"; t.print(); cout << " ";
swap(t);
return *this;
cout << endl;
}
void swap(Test& t)
{
cout << "swapping"; print();
cout << "and"; t.print();
std::swap(r, t.r);
cout << endl;
}
~Test()
{
cout << "destructor"; print();
free_res(r);
cout << endl;
}
resource* r;
};
int main()
{
Test t;
t = Test(5);
}
clang++ --std=c++11 -O0 -fno-elide-constructors test.cpp -o test
如果使用移动构造函数编译,则调用。(感谢切换,本杰明林德利)
现在的问题是:为什么它现在有效?有什么不同?