Oppinion on 'least priviledge', 'const correctness', etc.

Ö

Öö Tiib

I see what you mean. I think the following template class should
achieve this:

// Wrapper for plain pointers that behaves as const-correct
// accessor.
template<class t_Class>
class ConstCorrectAccessor
{
  t_Class* m_InternalPointer;
public:
  ConstCorrectAccessor (t_Class* Pointer)
    : m_InternalPointer (Pointer)
  {}

  // Accessor methods with const-correct overload.
  const t_Class* operator-> () const {return m_InternalPointer;}
  t_Class* operator ->() {return m_InternalPointer;}

};

Yes, something like that ... operator*() is missing.
class SomeClass
{
public:
  void foo () const {}
  void bar () {}

};

class AnotherClass
{
public:
  ConstCorrectAccessor<SomeClass> SomeObject;
public:
  AnotherClass (SomeClass* Object)
    : SomeObject (Object)
  {}

  void foo () const
  {
    SomeObject->foo (); // OK
    SomeObject->bar (); // Error: Non-const method on SomeObject.
  }

};

int main ()
{
  SomeClass a;
  const AnotherClass b (&a);
  b.SomeObject->foo ();  // OK
  b.SomeObject->bar ();  // Compilation error: b is const

  AnotherClass c (&a);
  c.SomeObject->foo ();  // OK
  c.SomeObject->bar ();  // OK: c is not const

}

Do you know whether such a thing is part of the STL/boost?

No, but usually i want RAII as well for such a polymorphic component.
So i took "boost::scoped_ptr<>" and modified it into a
"component_ptr<>" with transitive constness. Probably it might be idea
to add custom deleter (like boost::shared_ptr<> has), since
polymorphic things are often created and destroyed by factories. Also,
custom deleter helps when wrapping some sort of "handle" (lets say
from some C library) into class.
 
J

Jorgen Grahn

What is so unclear about it?

My full paragraph was:

I really focused on the obvious non-ambiguity of "the const version of
the member function", and didn't bother to read the rest carefully. I
should have phrased that differently; sorry.

It also turns out it *was* ambiguous, because I wasn't thinking of
overloading members by const -- I was thinking of whether the const in

void Foo::bar() const { ... }

usually matters for efficiency.
Which is more efficient, this:

const char& operator[](unsigned index) const
{
return str[index];
}

or this:

char& operator[](unsigned index)
{
deep_copy_if_needed();
return str[index];
}

?

That's how a class using copy-on-write would need to be implemented.

Sure, that's a drastic difference.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top