This is a test of your knowledge of C++, not of your compiler's knowledge of C++. Using a compiler during this test will likely give you the wrong answers, or at least incomplete ones.
Given the following code:
class Base {
public:
virtual ~Base() {}
virtual void DoSomething() {}
void Mutate();
};
class Derived : public Base {
public:
virtual void DoSomething() {}
};
void Base::Mutate() {
new (this) Derived; // 1
}
void f() {
void* v = ::operator new(sizeof(Base) + sizeof(Derived));
Base* p = new (v) Base();
p->DoSomething(); // 2
p->Mutate(); // 3
void* vp = p; // 4
p->DoSomething(); // 5
}
- Does the first numbered line result in defined behavior? (Yes/No)
- What should the first numbered line do?
- Do the second and third numbered lines produce defined behavior? (Yes/No)
- Does the fourth numbered line produce defined behavior? If so, why? If not, why?
Does the fifth numbered line produce defined behavior? If so, why? If not, why?
What is the behavior of calling
void exit(int);
?
Given the following code:
struct T{};
struct B {
~B();
};
void h() {
B b;
new (&b) T; // 1
return; // 2
}
- Does the first numbered line result in defined behavior?
Is the behavior of the second line defined? If so, why? If not, why is the behavior not defined?
What is the behavior of
int& p = (int)0;
? Why does it have that behavior? Is this a null reference?What is the behavior of
p->I::~I();
ifI
is defined astypedef int I;
andp
is defined asI* p;
?
Source