Suppose I have a class that controls a pointer to an internal buffer:
class Foo { public: Foo(); ... private: std::vector<unsigned char> m_buffer; unsigned char* m_pointer; }; Foo::Foo() { m_buffer.resize(100); m_pointer = &m_buffer[0]; }
Now suppose I also correctly applied material from the 3rd level, including the copy constructor, which copies the internal buffer and then reassigns the pointer to a new copy of the internal buffer:
Foo::Foo(const Foo& f) { m_buffer = f.m_buffer; m_pointer = &m_buffer[0]; }
If I also implement move semantics, can I just copy the pointer and move the buffer?
Foo::Foo(Foo&& f) : m_buffer(std::move(f.m_buffer)), m_pointer(f.m_pointer) { }
In practice, I know that this should work, because the std::vector move constructor simply moves the internal pointer - it does not actually redistribute anything, so m_pointer still points to a valid address. However, I am not sure that the standard guarantees this behavior. Does the semantics of std::vector move to ensure that redistribution does not happen, and therefore all pointers / iterators to the vector are valid?
source share