I'm writing code with a lot of STL vectors in it. I think I've structured it so that it's all references and move constructors, but I'd like an automated way to be sure. Is there any way to get a warning or error whenever the copy constructor gets invoked?
I don't want to write my own vector class, or modify the STL headers. Please do not mark this duplicate of similar questions from people writing their own classes: I don't want to do that.
Apart from disabling the copy constructor and copy assignment operator of the type stored inside the vector, no you won't be able to disable vector copies without modifying the vector source code.
You do have a few options, however.
You can check whether the vector copy constructor is present in your binary; the optimizer should eliminate it if it isn't ever used.
You can instrument the copy constructor of the type contained inside the vector, and see how often it is called.
You can put a breakpoint on the copy constructor (or on one of the helper functions it calls, and check the call stack when hit to see if it was the copy constructor calling it).
Or you can temporarily wrap vector with your own class, and delete its copy constructor.
instead of writing your own vector
class you could make a class that derives from vector
and implements all the constructors except the copy constructor. then you would #define vector my_vector
.
obviously this should only done to find copy-constructor calls and then this code should be commented out. this should only be 50-100 lines instead of 1k lines for your own vector class.
You could use std::unique_ptr<std::vector>
, although there will be a little bit overhead for the indirection, and a lot of .
need to be changed to ->
. That will help you to prevent copying without any hack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With