C ++ Not copied unless

I believe that creating a class that is not copyable helps me with my code quality. I initially did this with boost :: noncopyable, but I found that VC ++ compiler errors are not as useful as with private members (double-clicking leads to the wrong place in the code).

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

In fact, he warned me that in several cases the classes were not passed as references where they should have been. So much so that I would very much like to get a warning even about classes that I just need to copy the construct.

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

Or maybe all together is better?

+7
source share
4 answers

Not sure if this is exactly what you want, but if you mark the explicit copy constructor, then the class cannot be passed by value or initialized with the copy, but you can copy-construct using direct initialization.

Presumably you want the assignment operator to be closed, perhaps it would be useful for him to use the NonAssignable base.

+6
source

I think you yourself called the ideal path.

I just remembered a neat (?) Little trick that I once played in another code base that I worked on:

 struct T { friend class SomeClientThatCanConstructT; T(T const&); private: T(T const&); }; 

As discussed in the comments, the following will not fly

<sub> You can choose an explicit name (e.g. CopyConstruct) and rely on RVO just as efficiently:

 struct T { inline T CopyConstruct() const { return *this; } inline T& AssignTo(T& dst) const { return dst = *this; } inline T& AssignFrom(const T& src) { return *this = src; } private: T(T const&); T& operator=(T const&); }; 

sub> hit>

+2
source

You can build the T construct by default and then add the assign method. This does not look completely optimal, indicating that you can view your copy needs.

0
source

I don't like the idea of ​​type constraints ( CopyConstructible is a heavily used concept in all of stdlib) because it can be misused. If you can build an object from another instance, it must be constructive. It also distracts the reader from important code without serving any real purpose.

Maybe a warning or debug statement that is triggered by the copy constructor is really what you are looking for?

0
source

All Articles