I would like to create class which can’t be copied, so I put copying constructor into the private section:
class NotCopyable
{
public:
NotCopyable(const double& attr1, const double& attr2) : _attr1(attr1), _attr2(attr2) {}
~NotCopyable(void) {}
private:
NotCopyable& operator=(const NotCopyable&);
NotCopyable(const NotCopyable&);
double _attr1;
double _attr2;
};
Everything is OK except when I would like to assign the array:
NotCopyable arr[] =
{
NotCopyable(1, 0),
NotCopyable(2, 3)
};
The compiler says that she can’t access copying constructor as it is in private section.
When I put it in public section:
class NotCopyable
{
public:
NotCopyable(const double& attr1, const double& attr2) : _attr1(attr1), _attr2(attr2) {}
~NotCopyable(void) {}
NotCopyable(const NotCopyable&)
{
std::cout << "COPYING" << std:: endl;
}
private:
NotCopyable& operator=(const NotCopyable&);
double _attr1;
double _attr2;
};
Program compiles without errors, but copying constructor isn’t called. So the question is: how do I forbid copying but still have possibility to assign arrays?
Your code
arr [] = { NotCopyable(1,2) };does request the copy constructor, at least formally. Practically the copy is usually elided, but that falls under the “as-if” rule, and the copy constructor still has to be accessible, even though ultimately it isn’t used. (In GCC you can say-fno-elide-constructorsto actually invoke the copy constructor.)You can’t solve this in C++03, where brace-initialization always necessitates a formal copy. In C++11 you can use brace initialization to direct-initialize array members, though:
This works even in the absence of an accessible copy constructor.