(C++) Exercise \#10: Obtaining a read-only (smart?) pointer
February 24, 2017 · View on GitHub
(C++)
Exercise #10: Obtaining a read-only (smart?) pointer
Difficulty: 1/10
Date added: 30th of March 2011
This exercise shows that working with smart pointers is not always easy...
This exercise is a continuation on Exercise #1: A foolproof function.
The problem
Following Exercise #1: A foolproof function a programmer has written the following class:
#include <boost/checked_delete.hpp> struct MyStruct { int m_x; private: ~MyStruct() {} friend void boost::checked_delete<>(MyStruct *); };
Writing such a class enables safe forward declarations and forces the user of this class to use smart pointers, which is a good thing [1].
This programmer wants to use a class managing a boost::shared_ptr of MyStruct, but he/she also wants to let the user obtain a read-only smart pointer/pointer.
The code below shows the choices and some lines that should and should not compile:
struct MyStructKeeper { MyStructKeeper() : m_s(new MyStruct) {} /* ??? */ Get() /* ??? */ private: boost::shared_ptr<MyStruct> m_s; }; int main() { MyStructKeeper k; /* ??? */ = k.Get(); const int x = s->m_x; //Must compile s->m_x = 0; //Should not compile delete s; //Should not compile }
What should the question marks be?
View the answer of this part of the exercise
References
- Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 13: 'Ensure resources are owned by objects. Use explicit RAII and smart pointers.