Exercises
These are some very basic exercises to refresh you on the basics of pointers
Question
Considering only performance, when should you pass small objects by value, reference and pointer?
struct SmallStruct { int i };
void foo(SmallStruct s);
void foo(SmallStruct& s);
void foo(SmallStruct* s);
Solution Click to expand
Question
Considering only performance, when should you pass large objects by value, reference and pointer?
struct LargeStruct { std::vector<int> i };
void foo(LargeStruct s);
void foo(LargeStruct& s);
void foo(LargeStruct* s);
Solution Click to expand
Question
Are there reasons to prefer one argument-passing mechanism to another?
Solution Click to expand
Question
What happens when passing a derived object as a base object?
class Base
{
public:
virtual ~Base() {}
virtual void foo() const { std::cout << "Base" << std::endl; }
};
class Derived : public Base
{
public:
virtual void foo() const { std::cout << "Derived" << std::endl; }
};
void bar1(Base b) { b.foo(); }
void bar2(Base& rB) { rB.foo(); }
void bar3(Base* pB) { pB->foo(); }
...
Derived d;
bar1(d);
bar2(d);
bar3(&d);
Solution Click to expand
Question
What are the performance implications of returning large objects by value, reference and pointer?
Foo return_by_value()
{ return Foo(); }
Foo& return_by_reference()
{
//KLUDGE: We can't return a reference to an object whose lifetime ends
// after this function exits. Therefore we declare a local static.
// There are even kludgier methods for dealing with this, however.
static Foo s_f;
s_f = Foo();
return s_f;
}
Foo* return_by_pointer()
{ return new Foo; }
Solution Click to expand
Question
What are the correctness concerns of using a local static to return by reference?
Foo& return_by_reference()
{
//KLUDGE: We can't return a reference to an object whose lifetime ends
// after this function exits. Therefore we declare a local static.
// There are even kludgier methods for dealing with this, however.
static Foo s_f;
s_f = Foo();
return s_f;
}
Foo& f1 = return_by_reference();
Foo& f2 = return_by_reference();
std::cout << "Are f1 and f2 equal? "
<< std::boolalpha << (f1 == f2) << std::endl; //Outputs true
Solution Click to expand
Question
Is there a difference in speed when stateful objects are involved?
struct Foo
{
Foo() : v(10000) {};
std::vector<int> return_by_value() const { return v; }
const std::vector<int>& return_by_reference() const { return v; }
const std::vector<int>* return_by_pointer() const { return &v; }
private:
std::vector<int> v;
};
Solution Click to expand
Question
How should we decide between return by reference or pointer?
Solution Click to expand
Question
What are the consequences of returning a local polymorphic object by value, reference and pointer?
Solution Click to expand
Question
When should we pass by value, reference and pointer?
Solution Click to expand
Question
When should we return by value, reference and pointer?