0

I'm trying to use the new C++11 move semantics, but the copy constructor gets called every time... Does anyone know what am I doing wrong? I'm using VS2012. Thanks in advance!

MemoryBlock::MemoryBlock(MemoryBlock& other)
: m_capacity(other.m_used), m_used(other.m_used), m_pointer(nullptr) {
    std::wcout << L"Copy constructor called" << std::endl;
    // ...
}

MemoryBlock& MemoryBlock::operator=(MemoryBlock& other) {
    std::wcout << L"Copy assignment called" << std::endl;
    if (this != &other) {
        // ...
    }
    return *this;
}

MemoryBlock::MemoryBlock(MemoryBlock&& other)
: m_capacity(other.m_capacity), m_used(other.m_used), m_pointer(other.m_pointer) {
    std::wcout << L"Move constructor called" << std::endl;
    // ...
}

MemoryBlock& MemoryBlock::operator=(MemoryBlock&& other) {
    std::wcout << L"Move assignment called" << std::endl;
    if (this != &other) {
        // ...
    }
    return *this;
}

MemoryBlock CreateRequest(const wchar_t *action) {
    MemoryBlock request;
    // ...
    return request;
}

int __cdecl wmain(int argc, wchar_t *argv[]) {
    // ...
    MemoryBlock request = CreateRequest(argv[1]);
    // ...
}
  • Where do you expect a move to take place and why ? – quantdev Jan 24 '15 at 19:19
  • 1
    Your copy-constructor isn't quite right, and will fail to work in some situations. The argument should be a reference to a constant, i.e. `const MemoryBlock& other` – Some programmer dude Jan 24 '15 at 19:21
  • You're right, [Joachim Pileborg](http://stackoverflow.com/users/440558/joachim-pileborg)! I was missing the const. After adding it, the move constructor started being called! Thanks! – André Rodrigues Jan 24 '15 at 19:51
  • @quantdev: the move takes place on the instance that is created inside the CreateRequest function, which is returned and used by the MemoryBlock's constructor in the main function. – André Rodrigues Jan 24 '15 at 19:55
  • 1
    I wouldn't expect a move here regardless due to NRVO. – Barry Jan 24 '15 at 21:04

0 Answers0