lundi 20 avril 2015

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

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?

Aucun commentaire:

Enregistrer un commentaire