(C++) Exercise \#11: Obtaining a std::vector of read-only (smart?) pointers
January 7, 2018 · View on GitHub
(C++)
Exercise #11: Obtaining a std::vector of read-only (smart?) pointers
Difficulty: 2/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 #10: Obtaining a read-only (smart?) pointer.
The problem
Following Exercise #10: Obtaining a read-only (smart?) pointer 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 std::vector of boost::shared_ptr of MyStruct, but he/she also wants to let the user obtain a std::vector of read-only smart pointers/pointers, that can be copied freely.
The code below shows the choices and some lines that should and should not compile:
#include <vector> #include <boost/checked_delete.hpp> #include <boost/shared_ptr.hpp> struct MyStruct { int m_x; private: ~MyStruct() {} friend void boost::checked_delete<>(MyStruct *); }; struct MyStructKeeper { std::vector</* ??? */> Get() const { /* ??? */ } private: std::vector<boost::shared_ptr<MyStruct> > m_v; }; int main() { MyStructKeeper k1; MyStructKeeper k2; std::vector</* ??? */> v1 = k1.Get(); const std::vector</* ??? */> v2 = k2.Get(); std::copy(v2.begin(),v2.end(),std::back_inserter(v1)); v1[0]->m_x = 0; //Should not compile delete v1[0].get(); //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.