In Visual Studio 2019, I am trying, without success, to implement the technique for making a class non-copyable shown for C++11, and later, at the accepted answer at How do I make this C++ object non-copyable?.
My class is,
class Foo {
public:
Foo();
Foo(std::string name);
~Foo();
std::string m_name;
static std::int32_t s_counter;
public:
Foo(const Foo& inFoo) = delete;
Foo& operator=(const Foo& inFoo) = delete;
};
The definition code is,
std::int32_t Foo::s_counter = 0;
Foo::Foo(void)
{
Foo::s_counter++;
std::cout << "Foo constructor. Count = " << Foo::s_counter << std::endl;
}
Foo::Foo(std::string name)
{
Foo::s_counter++;
m_name = name;
std::cout << "Foo " << m_name << " constructor. Count = " << Foo::s_counter << std::endl;
}
Foo::~Foo()
{
Foo::s_counter--;
std::cout << "Foo destructor. Count = " << Foo::s_counter << std::endl;
}
It is used in,
int main(int argc, char** argv) {
std::vector<Foo> fooVector;
{
Foo myFoo1{ Foo() };
fooVector.push_back(std::move(myFoo1));
Foo myFoo2{ Foo("myFoo2") };
fooVector.push_back(std::move(myFoo2));
}
if (Foo::s_counter < 0) {
std::cout << "Foo object count = " << Foo::s_counter << std::endl;
}
std::cin.get();
}
in which I have intentionally scoped the definition of myFoo1
and myFoo2
so as to get object count feedback.
When the copy constructor and assignment constructor are made public
, as shown, the compile error is "C2280 'Foo::Foo(const Foo &)': attempting to reference a deleted function". When they are made private, the compile error is "C2248 'Foo::Foo': cannot access private member declared in class 'Foo'".
I believe I am misinterpreting something in the original SO answer, but I cannot see what it is.