Lately I have been working through Meyers’ Effective C++ Third Edition. For a project I am currently working on I have had to create a class that I explicitly want to disallow the use of compiler generated functions. I implemented code using Item 6 in said book as a reference, the only major difference in that my class is Templated. The code for it is as follows
template <class T>
class Uncopyable
{
protected:
Uncopyable<T>(){}
virtual ~Uncopyable<T>(){}
private:
Uncopyable<T>(const Uncopyable<T>&);
Uncopyable<T>& operator=(const Uncopyable<T>&);
};
My test function.
class Test : private Uncopyable<Test>
{
public:
Test(){}
~Test(){}
inline void test()
{
std::cout << "blah" << std::endl;
}
private:
protected:
};
When used like this the code works completely as expected
int main(int argc, char* argv[])
{
Test t1, t2;
// Works as expected, doesnt allow copying of object
t2 = t1;
// and this works fine, no copying
Test t3 = t2;
// finally, works correctly no copying is allowed
Test t4(t1);
return 0;
}
When used like this however, the code compiles fine and copying can take place, when it should not be able to?
int main(int argc, char* argv[])
{
Test* t1 = new Test(), *t2;
t1->test();
// Works when it shouldnt work?
t2 = t1;
t2->test();
// same with this
Test* t3 = t2;
t3->test();
// and this
Test* t4(t1);
t4->test();
delete t1;
return 0;
}
I have tried it without the template class and the result is the same, so I don’t think that is the issue.
So SO, why is this allowed to happen? Is there an error in my code, or am I just understanding the concept wrong? Thanks.
You’re copying the pointer, not the object. Try this: