1. If you want to create a custom new operator that does some logging but otherwise does not change the functionality of new, what do you need to include?
new
malloc
free
2. Given the following chunk of code: #include <iostream> #include <memory> static int current_allocations = 0; void* operator new(size_t size){ current_allocations++; return malloc(size); } void operator delete(void* memory){ current_allocations--; free(memory); } int main(){ int* int_ptr = new int(5); std::string* str_ptr = new std::string("foo"); delete int_ptr; std::unique_ptr<double> double_ptr = std::make_unique<double>(3.14); std::cout << current_allocations << std::endl; delete str_ptr; } What is the output of the code, and does it have a memory leak?
#include <iostream>
#include <memory>
static int current_allocations = 0;
void* operator new(size_t size){
current_allocations++;
return malloc(size);
}
void operator delete(void* memory){
current_allocations--;
free(memory);
int main(){
int* int_ptr = new int(5);
std::string* str_ptr = new std::string("foo");
delete int_ptr;
std::unique_ptr<double> double_ptr = std::make_unique<double>(3.14);
std::cout << current_allocations << std::endl;
delete str_ptr;
3. Given the following code: template <int X, int Y> struct IntegerSum{ static constexpr int value = X + Y; }; How would we get the sum of 4 and 5?
template <int X, int Y>
struct IntegerSum{
static constexpr int value = X + Y;
};
IntegerSum<4,5>
IntegerSum<4,5>::value
IntegerSum(4,5)
IntegerSum(4,5)::value
IntegerSum<int, int>(4,5)
IntegerSum<int, int>(4,5)::value
4. What is the standard way to return a value from a metafunction?
return value;
GetValue()
5. Is it better to benchmark in debug or release mode?
assert
6. If we profile a scope that has a lot of code and see that it is taking longer than expected, which of the following is NOT typically an effective next step for identifying the problem?
7. Which of the following features helps to facilitate efficient pass-by-value for classes with a large memory footprint?
for
delete
8. What is the direct result of profiling your code?
9. Which of the following is a benefit of benchmarking your code?
10. Is the following code legal? If not, why not? constexpr int x = 20; if constexpr (x < 100) { std::cout << "You win!" << std::endl; } else { std::cout << "You lose: x = " << x.size() << std::endl; }
constexpr int x = 20;
if constexpr (x < 100) {
std::cout << "You win!" << std::endl;
} else {
std::cout << "You lose: x = " << x.size() << std::endl;
x < 100
if constexpr
std::cout
int
constexpr
Click Check Answers to identify any errors and try again. Click Show Answers if you also want to know which answer is the correct one.