Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I disable std::vector's copy constructor?

Tags:

c++

c++11

stl

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.

like image 737
dspeyer Avatar asked Aug 22 '14 19:08

dspeyer


3 Answers

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.

like image 151
Ben Voigt Avatar answered Oct 21 '22 13:10

Ben Voigt


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.

like image 22
programmerjake Avatar answered Oct 21 '22 12:10

programmerjake


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.

like image 2
GuLearn Avatar answered Oct 21 '22 12:10

GuLearn