Search code examples
c++noncopyable

C++ Non copyable except sometimes


I find that making a class non-copyable helps me a lot with my code quality. Initially I did this with boost::noncopyable, but I found the VC++ compiler errors to be not as helpful as with private members (double clicking lead to the wrong place in the code).

T(T const&);
T& operator=(T const&);

Indeed, it has alerted me to quite a few cases were classes were not passed as reference where they should have. So much so, that I would very much like to get a warning even on classes that I just need to copy construct once.

Is there a good way to do this? I was thinking for example of leaving above two methods private and adding a public T(T const&,bool dummy) constructor to call when I really want to copy construct. Or maybe alternatively make above two methods public and somehow activate a compiler warning when copy constructing, suppressing the warning where I do want to.

Or maybe there is an all together better way?


Solution

  • Not sure if it's exactly what you want, but if you mark the copy constructor explicit then the class can't be passed by value or copy-initialized, but you can copy-construct using direct initialization.

    You'd presumably want to keep the assignment operator private, maybe a NonAssignable base would be useful for that.