Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent object from being copied by std::memcpy?

Tags:

c++

memory

c++11

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?

like image 370
Nykakin Avatar asked Apr 20 '15 21:04

Nykakin


People also ask

How do you prevent an object from being copied in C++?

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.

What can I use instead of memcpy?

memmove() is similar to memcpy() as it also copies data from a source to destination.

Can we use memcpy in C++?

The memcpy() function in C++ copies specified bytes of data from the source to the destination. It is defined in the cstring header file.

What is std :: memcpy?

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.


1 Answers

Can I prevent object from being copied by std::memcpy?

The simple answer is "No".

like image 54
R Sahu Avatar answered Nov 09 '22 10:11

R Sahu