M
Micha³ 'Khorne' Rzechonek
Hello,
I wanted o understand how rvalue references work, so I took GCC 4.3
with -std=c++0x flag and wrote code below.
What I don't understand is why 2nd assertion fails and move ctor is
not
called. Please enlighten me
Side question: does source() function look all right?
#include <iostream>
#include <cassert>
using std::cout;
using std::endl;
using std::move;
template<typename T>
class unique_ptr {
public:
explicit unique_ptr(T *&&a_ptr): m_ptr(a_ptr) {
a_ptr = NULL;
}
unique_ptr(unique_ptr &&p): m_ptr(p.release()) {
cout << "Move" << endl;
}
T *release() {
T *ptr = m_ptr;
m_ptr = NULL;
return ptr;
}
T *get() {
return m_ptr;
}
T *operator->() {
return m_ptr;
}
~unique_ptr() {
if(m_ptr != NULL) {
delete m_ptr;
}
}
private:
unique_ptr(const unique_ptr &);
void operator=(const unique_ptr &);
void operator=(unique_ptr &&p);
T *m_ptr;
};
struct Foo
{
Foo(int a): a(a) {
cout << "Foo::ctor(" << a << ")" << endl;
}
~Foo() {
cout << "Foo::dtor()" << endl;
}
int a;
private:
Foo(const Foo &);
Foo(Foo &&);
};
unique_ptr<Foo> source(int a = 0) {
return move(unique_ptr<Foo>(new Foo(a)));
}
void sink(unique_ptr<Foo> a_foo) {
cout << a_foo->a << endl;
}
int main() {
unique_ptr<Foo> foo( source(1) );
unique_ptr<Foo> bar = move(foo);
assert(foo.get() == NULL); // ok
unique_ptr<Foo> qux( source(2) );
sink( move(qux) );
assert(qux.get() == NULL); // ??
}
I wanted o understand how rvalue references work, so I took GCC 4.3
with -std=c++0x flag and wrote code below.
What I don't understand is why 2nd assertion fails and move ctor is
not
called. Please enlighten me
Side question: does source() function look all right?
#include <iostream>
#include <cassert>
using std::cout;
using std::endl;
using std::move;
template<typename T>
class unique_ptr {
public:
explicit unique_ptr(T *&&a_ptr): m_ptr(a_ptr) {
a_ptr = NULL;
}
unique_ptr(unique_ptr &&p): m_ptr(p.release()) {
cout << "Move" << endl;
}
T *release() {
T *ptr = m_ptr;
m_ptr = NULL;
return ptr;
}
T *get() {
return m_ptr;
}
T *operator->() {
return m_ptr;
}
~unique_ptr() {
if(m_ptr != NULL) {
delete m_ptr;
}
}
private:
unique_ptr(const unique_ptr &);
void operator=(const unique_ptr &);
void operator=(unique_ptr &&p);
T *m_ptr;
};
struct Foo
{
Foo(int a): a(a) {
cout << "Foo::ctor(" << a << ")" << endl;
}
~Foo() {
cout << "Foo::dtor()" << endl;
}
int a;
private:
Foo(const Foo &);
Foo(Foo &&);
};
unique_ptr<Foo> source(int a = 0) {
return move(unique_ptr<Foo>(new Foo(a)));
}
void sink(unique_ptr<Foo> a_foo) {
cout << a_foo->a << endl;
}
int main() {
unique_ptr<Foo> foo( source(1) );
unique_ptr<Foo> bar = move(foo);
assert(foo.get() == NULL); // ok
unique_ptr<Foo> qux( source(2) );
sink( move(qux) );
assert(qux.get() == NULL); // ??
}