Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...