It's easy to make noncopyable class with private copy construcor and assignment operator, boost::noncopyable
or the C++11 delete
keyword:
class MyClass {
private:
int i;
public:
MyClass(const MyClass& src) = delete;
MyClass& operator=(const MyClass& rhs) = delete;
int getI() {
return i;
}
MyClass(int _i) : i(_i){}
};
int main() {
MyClass a(1), b(2);
a = b; // COMPILATION ERROR
}
However this doesn't prevent obiect from being deep copied as a pack of bytes:
int main() {
MyClass a(1), b(2);
std::memcpy(&a, &b, sizeof(MyClass));
std::cout << a.getI() << std::endl; // 2
}
Even if try to prevent it by declaring operator&
private, it's still possible to make copy using implementations of address-of idiom:
int main() {
MyClass a(1), b(2);
std::memcpy(std::addressof(a), std::addressof(b), sizeof(MyClass));
std::cout << a.getI() << std::endl; // 2
}
Is there any method to completely prevent an instance from being copied byte per byte?
There are three ways to prevent such an object copy: keeping the copy constructor and assignment operator private, using a special non-copyable mixin, or deleting those special member functions. A class that represents a wrapper stream of a file should not have its instance copied around.
memmove() is similar to memcpy() as it also copies data from a source to destination.
The memcpy() function in C++ copies specified bytes of data from the source to the destination. It is defined in the cstring header file.
std::memcpyCopies count bytes from the object pointed to by src to the object pointed to by dest . Both objects are reinterpreted as arrays of unsigned char. If the objects overlap, the behavior is undefined. If either dest or src is an invalid or null pointer, the behavior is undefined, even if count is zero.
Can I prevent object from being copied by
std::memcpy
?
The simple answer is "No".
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