Value representation of non-trivially copyable types

只愿长相守 提交于 2019-12-18 06:25:30

问题


I'm intrigued by the following paragraph from the standard (§3.9/4 of ISO/IEC 14882:2011(E)):

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T). The value representation of an object is the set of bits that hold the value of type T. For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.42

I understand that the object representation and value representation are distinct to allow some of the object representation to not take part in the value of the object (for example, padding). I don't quite get the point about trivially copyable types though. Do non-trivially copyable types not have values? Can part of the value representation of a non-trivially copyable type exist outside its object representation?

Note 42 explains:

The intent is that the memory model of C++ is compatible with that of ISO/IEC 9899 Programming Language C.

I still don't understand why the previous statement is specifically for trivially copyable types only though. What is the significance of this?


回答1:


The standard example is a class that manages a resource:

struct Foo
{
    Bar * p;

    Foo() : p(new Bar) { }
    ~Foo() { delete p; }

    // copy, assign
};

An object of type Foo has a value, but that value is not copyable by copying the object representation (which is just the value of p in this case). Copying an object of type Foo requires copying the se­man­tics of the class, which say "an object owns the pointee". A suitable copy thus requires an appropriate, user-defined copy constructor:

Foo::Foo(Foo const & rhs) : p(new Bar(*rhs.p)) { }

Now the object representation of an object of type Foo is different from the object representation of a copy of such an object, although they have the same value.

By contrast, the value of an int is the same as that of another int as soon as the object representations coincide. (This is a sufficient, though not necessary, condition, due to padding.)



来源:https://stackoverflow.com/questions/12773640/value-representation-of-non-trivially-copyable-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!