0% found this document useful (0 votes)
9 views6 pages

Advanced CPP Exam B Full

This document outlines the structure and content of an examination for Advanced Programming in C++, including multiple-choice questions, code analysis, short-answer questions, code fill-in tasks, and programming problems. The exam targets ISO C++17 and covers various advanced topics such as constexpr, memory management, and template programming. It consists of five parts, totaling 150 points, with a duration of 150 minutes.

Uploaded by

tlan44326
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Advanced CPP Exam B Full

This document outlines the structure and content of an examination for Advanced Programming in C++, including multiple-choice questions, code analysis, short-answer questions, code fill-in tasks, and programming problems. The exam targets ISO C++17 and covers various advanced topics such as constexpr, memory management, and template programming. It consists of five parts, totaling 150 points, with a duration of 150 minutes.

Uploaded by

tlan44326
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Advanced Programming in C++ –

Examination B (Full Version)


(Duration : 150 min · Total Score : 150 pts)

Answer in English on the answer sheet provided. Unless otherwise


stated, the code targets ISO C++17.

Part I · Multiple-Choice (20 × 2 pts = 40 pts)


Choose the one best answer for each item.

1. 1. A constexpr destructor is ill-formed unless


A. all base classes are literal types
B. its body is = default; and performs no delete
C. the class is trivially destructible
D. the object is created in constant evaluation
2. 2. std::vector<int> v{1,2,3}; v.erase(v.begin()+1); is valid because the iterator originates
from
A. random-access category
B. an owned container and is not invalidated until after erase returns
C. contiguous-iterator model required by C++17
D. the allocator’s rebound type
3. 3. Two classes each virtually inheriting Base will share
A. exactly one v-ptr per sub-object
B. exactly one Base sub-object in their common most-derived object
C. two independent v-tables but one v-ptr
D. implementation-defined storage
4. 4. Which of the following disables ADL (argument dependent lookup)?
A. placing the function in namespace std
B. adding a templated non-type parameter
C. putting the call within a class scope and using this->f(...)
D. calling the function through a qualified name such as ::f
5. 5. A class that obeys the Rule-of-Zero must explicitly declare
A. none of the special member functions
B. a virtual destructor only
C. move constructor and move assignment
D. copy constructor and copy assignment
6. 6. std::move_if_noexcept(x) will move when
A. move constructor is noexcept OR copy constructor is deleted
B. move constructor may throw
C. copy constructor is constexpr
D. both copy and move are noexcept
7. 7. A constexpr constructor may include which of the following?
A. try-block with catch
B. dynamic_cast on polymorphic type
C. static_assert
D. asm volatile
8. 8. Which call correctly visits a std::variant<int,std::string> with a generic lambda?
A. std::visit([](auto&& v){}, var);
B. var.visit([](auto&& v){}, var);
C. std::apply([](auto&& v){}, var);
D. visit(var, [](auto&& v){});
9. 9. Memory order acquire-release ensures
A. sequential consistency across all threads
B. writes in the releasing thread become visible to the acquiring thread
C. no reordering of independent loads
D. automatic fence insertion on all architectures
10. 10. In C++20 modules, the keyword that marks a translation unit as a module interface
is
A. module;
B. export module;
C. import;
D. export;
11. 11. In a coroutine, the first suspension point after co_await is determined by
A. promise_type::get_return_object
B. await_ready()
C. await_suspend()
D. await_resume()
12. 12. An allocator-aware container constructs an element using which expression?
A. ::new (p) T(args...);
B. allocator_traits<A>::construct(alloc,p,args...);
C. std::construct_at(p,args...);
D. std::allocator_traits<T>::construct(p,args...);
13. 13. Which expression yields an xvalue of type std::string?
A. "abc"s
B. std::move(std::string("abc"))
C. std::string("abc").c_str()
D. std::string("abc").data()
14. 14. A friend function defined inside a class body is found by
A. normal lookup only
B. argument dependent lookup only
C. both normal and ADL
D. depends on inline specifier
15. 15. Ignoring the return value of a [[nodiscard]] function triggers
A. linkage error
B. compile-time diagnostic, typically a warning
C. undefined behaviour
D. runtime exception std::logic_error
16. 16. std::atomic_ref<T> differs from std::atomic<T> in that it
A. may alias other non-atomic accesses to the same object
B. provides lock-free operations on every type
C. stores its own memory separate from the referenced object
D. cannot be used with aggregate types
17. 17. A concept can be used to constrain
A. non-template functions only
B. variable templates only
C. both type and non-type template parameters
D. only class templates
18. 18. What is the dynamic extent of std::span<int> s(vec.data(), vec.size()) ?
A. size fixed at compile time
B. size stored in the span object at runtime
C. size stored in the vector
D. no size information is kept
19. 19. Which std::filesystem function removes an empty directory and returns true on
success?
A. remove_all
B. remove
C. erase
D. rmdir
20. 20. std::launder is required when
A. reinterpreting an object through a char* pointer
B. accessing a new object in storage that previously held a different object of same
type
C. using placement new to construct a trivially relocatable object
D. converting between base and derived pointers

Part II · Read-the-Code & Predict Output (5 × 8 pts = 40 pts)


For each program segment, write exactly what is printed to stdout.

 Listing 1

// II-1 Template static counters + link-time order


#include <iostream>
template<int ID> struct Counter {
static int value;
Counter() { std::cout << ID << ':' << ++value << ' '; }
};
template<int ID> int Counter<ID>::value = 0;
Counter<1> g1; // global
int main() {
static Counter<1> s1; // function-local static
Counter<2> l1; // local automatic
}

 Listing 2

// II-2 Diamond with two virtual bases + throw in constructor


#include <iostream>
struct B { B(){std::cout<<'B';} ~B(){std::cout<<'b';} };
struct V1 : virtual B { V1(){std::cout<<'1';} ~V1(){std::cout<<'!';} };
struct V2 : virtual B { V2(){std::cout<<'2';} ~V2(){std::cout<<'?';} };
struct D : V1, V2 { D(){std::cout<<'D'; throw 0;} ~D(){std::cout<<'d';} };
int main(){ try{ D d; }catch(...){ std::cout<<'X'; } }

 Listing 3

// II-3 Lambda capture mutability + life-extension


#include <iostream>
auto make() { return [x = std::string("hi")](auto&& self)->void {
std::cout << x << ' '; x += '!';
if(x.size()<5) self(self);
}; }
int main(){ auto f = make(); f(f); }

 Listing 4

// II-4 Pointer-to-member & multiple inheritance offsets


#include <iostream>
struct A{ int a=1; };
struct B{ int b=2; };
struct C: A,B{ int c=3; };
int main(){ C c; int B::* pb=&B::b; std::cout<< c.*pb; }

 Listing 5

// II-5 promise / future race – interleaved threads


#include <future>
#include <iostream>
int main(){
std::promise<int> p; auto f=p.get_future();
std::thread t([&]{ p.set_value(1); });
std::cout<< f.get();
t.join();
}

Part III · Short-Answer (8 × 4 pts = 32 pts)


21. 1. Why can’t a constructor be declared virtual? Describe both the language rule and the
object-lifetime rationale.
22. 2. Compare a constrained template using C++20 requires with the older SFINAE idiom
based on enable_if.
23. 3. Explain how placement-new plus an explicit destructor enables object pools, and list
two hazards.
24. 4. Under what conditions is it legal to reinterpret_cast the result of operator new(size)
to a stricter-aligned pointer type?
25. 5. Define a literal type and state why std::vector<T> can never be literal, regardless of T.
26. 6. Give two reasons why throwing inside a destructor during stack-unwinding leads to
program termination.
27. 7. Distinguish the memory orders acquire, release, and acq_rel in std::atomic.
28. 8. Sketch how co_await transforms into a state machine at compile time (promise type,
awaitable, resume point).

Part IV · Code Fill-in (16 blanks × 2 pts = 32 pts)


 Complete the missing fragments (___?___) in span2d.hpp so the following driver compiles
and prints OK 6 times.

#include "span2d.hpp"
#include <array>
#include <iostream>
constexpr std::array<int,9> buf {1,2,3,4,5,6,7,8,9};
int main(){
constexpr span2d<int> m(buf.data(),3,3);
static_assert(m(1,1)==5);
constexpr auto sub = m.subspan(1,1,2,2);
static_assert(sub(0,0)==5 && sub(1,1)==9);
span2d<const int> ro(m);
std::cout << "OK";
}

Part V · Programming Problems (3 tasks = 34 pts)


29. V-1 (8 pts) — Compile-Time Rational
Implement template rat<N,D> storing a reduced rational at compile time. Provide
constexpr + – * / == <=> and constexpr double value() const.
30. V-2 (12 pts) — Small Thread Pool
Write class thread_pool: fixed size set in ctor; submit<F>(F) returns
std::future<invoke_result_t<F>>; shut-down in dtor joins all workers; copy/move
deleted. Demonstrate summing 1…1 000 000 in parallel.
31. V-3 (14 pts) — Polymorphic Geometry Hierarchy
Create abstract base Shape with pure virtual area() and clone(). Provide Circle,
Rectangle, Triangle. Store std::unique_ptr<Shape> in a vector; implement deep copy via
clone(). Overload operator<< for text output. Supply main() that reads shapes, clones
collection, prints total area.

End of Examination B – Good luck!

You might also like