I am attempting to delete the copy constructor using the c++ type system to prevent copying an object.
struct DeleteCopyConstructor {
DeleteCopyConstructor() {};
DeleteCopyConstructor(DeleteCopyConstructor& op2) = delete;
DeleteCopyConstructor(const DeleteCopyConstructor& op2) = delete;
};
DeleteCopyConstructor f() {
DeleteCopyConstructor d;
// initialize d...
return d;
}
The error is:
error: use of deleted function ‘DeleteCopyConstructor::DeleteCopyConstructor(const DeleteCopyConstructor&)’
I've read about copy elision, but it appears to be a compiler optimization, so I don't think it applies. How can I return d
without triggering copy construction?
That's what your reference is talking about. No values are replaced, the copy constructor is called in order to intialize one object as a duplicate of another, separate object of the same type. However, it is not so simple as the copy constructor always being called when an object is returned.
A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.
Whenever you return a local object of a function, the compiler tends to keep and redirect the local object to the place you return (so the local object won't be deleted and compiler need not to create another object to copy the detail of the local object.) After the statement finishes (;),the local object is then deleted.
The following article discusses the way to return a local variable created inside a function, which can be done by returning a pointer to the variable from the called function to the caller function. What happens when you try to return a local variable as usual?
In C++17 the compiler is guaranteed to elide the copy. However in all cases you still need to have a valid copy constructor.
So if you're just concerned about performance then you don't have to do anything. If you want to delete the copy constructor because the value logically shouldn't be copyable then there is no way to do it as far as I know. You'd have to return a std::unique_ptr<T>
or take the value by reference and move into it that way. Edit: Or define a move constructor.
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