Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value representation of non-trivially copyable types

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?

like image 507
Joseph Mansfield Avatar asked Oct 07 '12 23:10

Joseph Mansfield


1 Answers

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.)

like image 127
Kerrek SB Avatar answered Nov 15 '22 06:11

Kerrek SB