Copy semantics (part 1)
On this page
Shallow vs. deep copy
Questions
Q1
QCopy semantics, Q1
This question is ungraded.
If the MyStruct type is implemented such that a deep copy is made upon initializing an
MyStruct object with an object of the same type, what is the output of this program?
struct MyStruct {
size_t number;
char* letter;
MyStruct() = default;
MyStruct(const MyStruct& source) { /* implementation hidden */ }
};
int main() {
MyStruct foo;
foo.number = 5;
foo.letter = new char('z');
MyStruct bar = foo;
*(bar.letter) = 'b';
std::cout << foo.letter << std::endl; // What will this print?
}
Q2
QCopy semantics, Q1
This question is ungraded.
If the MyStruct type is implemented such that a shallow copy is made upon initializing an
MyStruct object with an object of the same type, what is the output of this program?
struct MyStruct {
size_t number;
char* letter;
MyStruct() = default;
MyStruct(const MyStruct& source) { /* implementation hidden */ }
};
int main() {
MyStruct foo;
foo.number = 5;
foo.letter = new char('z');
MyStruct bar = foo;
*(bar.letter) = 'b';
std::cout << foo.letter << std::endl; // What will this print?
}
Q3
QCopy semantics, Q3
This question is ungraded.
The default copy mechanism for an object of a user-defined type
using an instance of the same type is a memberwise copy. In the lesson, we state
that the copy mechanism for a memberwise copy is a .
Q4
QCopy semantics, Q4
This question is ungraded.
A
means that the object is copied exactly as it is: data member values are copied exactly
to the other object's corresponding data member.
Q5
QCopy semantics, Q5
This question is ungraded.
When there is a pointer inside an object that points to dynamic data, a of that object is may not be sufficient since:
- Only the values from pointers are copied into the other object’s corresponding pointers, but not the dynamic data that is pointed to.
- Consequently, the copy will be pointing to the original dynamic data.
- This results in the dynamic data being shared between the objects.
Q6
QCopy semantics, Q6
This question is ungraded.
In a ,
the objects pointed to in one object are first copied. Then the other object’s corresponding pointers are
assigned the addresses of the copied objects.
Q7
QCopy semantics, Q7
This question is ungraded.
After a
as been completed, each object's free store pointers point to the same values stored in different
dynamically allocated objects; there is no dynamic data being shared between the objects.