为了在处理数组成员时理解移动运算符,我编写了以下开发测试。
当我通过不实现赋值或移动赋值运算符而违反了 5 规则时,为什么这会起作用和/或编译?
我目前正在使用 Visual Studio 2015。
#include <cstring>
#include <iostream>
#include <string>
struct Foo
{
Foo(const char * cstring, const std::string & string)
:
m_string(string)
{
strncpy_s(m_cstring, sizeof(m_cstring), cstring, _TRUNCATE);
}
Foo(const Foo & rhs)
:
m_string(rhs.m_string)
{
std::copy(rhs.m_cstring, rhs.m_cstring + sizeof(rhs.m_cstring), m_cstring);
}
Foo(Foo && rhs)
:
m_string(std::move(rhs.m_string))
{
std::copy(rhs.m_cstring, rhs.m_cstring + sizeof(rhs.m_cstring), m_cstring);
}
char m_cstring[6];
std::string m_string;
};
int main()
{
// Initialize
Foo a("Hello", "World");
// Copy constructor
Foo b(a);
std::cout << &a.m_cstring << " " << a.m_cstring << " " << a.m_string << std::endl;
std::cout << &b.m_cstring << " " << b.m_cstring << " " << b.m_string << std::endl << std::endl;
// Move constructor
Foo c(std::move(a));
std::cout << &c.m_cstring << " " << c.m_cstring << " " << c.m_string << std::endl << std::endl;
// Assignment operator
Foo d = c;
std::cout << &c.m_cstring << " " << c.m_cstring << " " << c.m_string << std::endl;
std::cout << &d.m_cstring << " " << d.m_cstring << " " << d.m_string << std::endl << std::endl;
// Move Assignment operator
Foo e = std::move(c);
std::cout << &e.m_cstring << " " << e.m_cstring << " " << e.m_string << std::endl << std::endl;
return 0;
}