c++ - C++11 const correctness for raw pointer getter -



c++ - C++11 const correctness for raw pointer getter -

i've come across little issue const correctness in c++11 hoping clarified--i don't think has been asked!

assume have class a, contains instance of class b want expose. if exposed reference provide both const , non-const versions of getter:

class b; class final { public: b& getb() { homecoming m_b; } const b& getb() const { homecoming m_b; } private: b m_b; };

however if had pointer b provide getter const returned re-create of pointer non-const instance of b. because doesn't own b, owns the pointer, , hence external modification of b doesn't alter state of a. (note: i've come conclusion personal experience; i've never found explicitly stating how should work)

class b; class final { public: a(b* b) { m_b = b; } a* getb() const { homecoming m_b; } private: b* m_b; };

this makes sense far, if owns unique pointer (or shared pointer matter) b? logically owns b--even if not literally. until i've been next sec illustration above when exposing raw pointer shared pointer, since logically owns b should doing more similar first example?

class b; class final { public: a(std::unique_ptr<b> b) { m_b = std::move(b); } b* getb() { homecoming m_b.get(); } const b* getb() const { homecoming m_b.get(); } private: std::unique_ptr<b> m_b; };

for ownership situation imho unnatural if fellow member function allow modification of part of logically const object, that's design issue.

however, note raw pointer can used implement ownership.

for example, consider internal array implemented direct new-ing , raw pointer. not want interface break when/if replaced std::vector handling storage. , rule whether provide const/non-const pair of accessor functions must rooted in design level, not in language permits given implementation of design.

c++ pointers c++11 const

Comments

Popular posts from this blog

c# - ASP.NET MVC Sequence contains no matching element -

java - Parsing XML, skip certain tags -

rest - How to invalidate user session on inactivity in a stateless server? -