+ 1
Can we stop pointer assignment any way ?
Hi We can delete copy constructor or copy assignment and it stops copying objects. What to do if we want to stop copying pointers ? Base* pb = new Base; auto pb2 = pb;//this should not compile
7 odpowiedzi
+ 3
Dunno, but I am thinking maybe there is a way to override the assignment operator to exclude pointer types.
+ 3
Ketan Lalcheta, I resorted to ChatGPT for an answer. Below is the short version of its answer and a link to its solution. On the surface it seems to work. As I am only the messenger I disclaim any credit or blame for the outcome!
ChatGPT:
"The Only Way to Prevent This
To stop pointer assignments like auto b3 = b1, you'd need to wrap the pointer in a class, and then delete the copy constructor or assignment operator of that wrapper."
https://sololearn.com/compiler-playground/cWVC9bp4XfMg/?ref=app
+ 1
Brian, you are able to stop copying but the syntax Base* and NoCopy<Base>* or NoCopy<Base*> is what the OP want to control
+ 1
RuntimeTerror
no, I think Brian's code doing what's intended.
the wrapper class is similar to Python's decorator. It's providing additional functionality to the Base and Derived classes.
It's not possible to implement pointer copy prevention directly in the Base or Derived classes, but it's possible through wrappers or decorator pattern. The Base and Derived classes should not be used directly but have to go through the NoCopyPtr template class.
Ketan Lalcheta
I think if the code is yours, or you're with a small enough team, a prominent comment warning not to copy the pointer would be sufficient instead of introducing this complexity...
or use unique_ptr....
+ 1
Brian I got it
+ 1
Thanks Brian
0
It's not possible. Pointers are primitive just like int and others