C++: -> operator overloading: Handle const / nonconst access differently - c++

I'm building a reference counting system and have defined a prototype template class which represents all references to objects that will be used.
The point where I am stuck is that I have to differentiate between const and non const access to those objects through a reference. If the access is const (read-only, or called method of underlying object is flagged const), everything is okay - however if it's not - a copy of the object might have to be created first.
A simplified version of my reference class:
template< class T >
class CRef
{
protected:
T* ptr;
public:
T* const* operator ->() const { return ptr; };
T* operator ->() { printf( "Non-const access!" ); return ptr; };
};
The problem is, that only the non-const -> operator overload function gets called, even when accessing const functions of the underlying object type.
How do I get the constant dereferencing overloading function to get called properly?

The const one is called on const objects. If you want the const -> called, cast the object reference you have to a const or provide a way to get a const version of the object.

const / non-const cannot, in principle, be used to differentiate between read and write access.
You’re out of luck here. The only way to accomplish this is via a proxy object that is returned by operator -> and that handles reading via an implicit conversion:
The returned proxy defines an operator T (implicit conversion) that is invoked when it is assigned to another object, and an operator =(T const&) when something is assigned to it.
template <typename T>
class CRef {
…
CRefElementProxy<T> operator ->() const { return CRefElementProxy<T>(this); };
friend CRefElementProxy;
};
template <typename T>
class CRefElementProxy {
operator T const*() const { return parent->ptr; }
CRefElementProxy operator =(T const* value) {
printf("Non-const access!");
return parent->ptr;
}
};
That’s just a pseudo-codey draft. The real version looks a bit more complex.

Once the pointer has been returned then there is no way to know what is done with it.

Related

Const and non-const accesors, which will be called [duplicate]

I tried to wrap something similar to Qt's shared data pointers for my purposes, and upon testing I found out that when the const function should be called, its non-const version was chosen instead.
I'm compiling with C++0x options, and here is a minimal code:
struct Data {
int x() const {
return 1;
}
};
template <class T>
struct container
{
container() {
ptr = new T();
}
T & operator*() {
puts("non const data ptr");
return *ptr;
}
T * operator->() {
puts("non const data ptr");
return ptr;
}
const T & operator*() const {
puts("const data ptr");
return *ptr;
}
const T * operator->() const {
puts("const data ptr");
return ptr;
}
T* ptr;
};
typedef container<Data> testType;
void testing() {
testType test;
test->x();
}
As you can see, Data.x is a const function, so the operator -> called should be the const one. And when I comment out the non-const one, it compiles without errors, so it's possible. Yet my terminal prints:
"non const data ptr"
Is it a GCC bug (I have 4.5.2), or is there something I'm missing?
If you have two overloads that differ only in their const-ness, then the compiler resolves the call based on whether *this is const or not. In your example code, test is not const, so the non-const overload is called.
If you did this:
testType test;
const testType &test2 = test;
test2->x();
you should see that the other overload gets called, because test2 is const.
test is a non-const object, so the compiler finds the best match: The non-const version. You can apply constness with static_cast though: static_cast<const testType&>(test)->x();
EDIT: As an aside, as you suspected 99.9% of the time you think you've found a compiler bug you should revisit your code as there's probably some weird quirk and the compiler is in fact following the standard.
It doesn't matter whether Data::x is a constant function or not. The operator being called belongs to container<Data> class and not Data class, and its instance is not constant, so non-constant operator is called. If there was only constant operator available or the instance of the class was constant itself, then constant operator would have been called.
But testType is not a const object.
Thus it will call the non const version of its members.
If the methods have exactly the same parameters it has to make a choice on which version to call (so it uses the this parameter (the hidden one)). In this case this is not const so you get the non-const method.
testType const test2;
test2->x(); // This will call the const version
This does not affect the call to x() as you can call a const method on a non const object.

Why can I pass by value here but not by reference (C++)?

I have an interesting predicament here where the code will compile if I pass a variable by value to the function but not if I pass it by reference, and I'm not sure why. In header.h:
#include <iostream>
#include <string>
void get_name(std::string &name)
{
getline(std::cin, name);
return;
}
template <class T, class U>
class readonly
{
friend U;
private:
T data;
T& operator=(const T& arg) {data = arg; return data;}
public:
operator const T&() const {return data;}
};
class myClass
{
private:
typedef readonly<std::string, myClass> RO_string;
public:
RO_string y;
void f()
{
get_name(y); // compile error
}
};
The main.cpp implementation file simply includes this header file, creates an instance of myClass and then calls f(). When doing so, it won't compile properly. The problem lies in the fact that I'm passing the variable y by reference to the get_name function. If I change the function so that I pass by value instead, everything compiles properly and works as expected (except I'm obviously not making changes to y anymore). However, I don't understand this behavior. Why does this happen and is there an optimal way to fix it in this situation?
Your conversion operator:
operator const T&() const {return data;}
Only allows implicit conversion to a const reference. This makes sense since you are interested in making something read only. But get_name requires a non-const reference to a string. That is, get_name expects to be able to mutate its input. The type being passed in cannot convert to a mutable string reference, only to a constant string reference, so it doesn't compile.
When you pass by value, it simply constructs a new string from the const reference to pass into the function, which is fine.
Intuitively, a function called get_name should probably take a const reference since it shouldn't need to mutate its input just to get the name.
As explained by Nir Friedman, get_name(y); invoques the implicit conversion operator which gives you a const reference.
But, as you wrote friend U;, myClass has access to the private member data of y and allows you to do:
get_name(y.data);

What does ClassName& as a return type mean?

I try to understand the following code (taken from here):
template <class T> class auto_ptr
{
T* ptr;
public:
explicit auto_ptr(T* p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
T& operator*() {return *ptr;} // <----- The problematic row.
T* operator->() {return ptr;}
// ...
};
I cannot understand what do we mean when we use T& as a return type of a function. If T is a pointer to an integer (or any other type), then I would interpret T& as integer (or any other corresponding type). But in the above given code T is not a pointer. T is a class, and one of its members (ptr) is a pointer to objects of this class but T is not a class of pointers. So, what does T& as a return type mean?
It means the same as outside the context of a function's return type, i.e. T& is a reference to T. In this case, the function returns a reference to an object of type T that the caller can use to observe (and also alter, if T is not const-qualified) the referenced object.
T& is simply a reference to type T. the function returns a reference to an object of class T.
T is a class, and one of its members (ptr) is a pointer to objects of this class but T is not a class of pointers.
ptr is not a member of class T. It is a member of class auto_ptr<T>.
ptr is a pointer to T. But the fact that T is not a "class of pointers"
(whatever that means) does not prevent something being a pointer to a T.
std::string is a class - of strings, not pointers.
std::string str; is an object of class std::string.
&str is the address of str
std::string * ps = &str;
is a pointer to an std::string.
From the top:
template <class T> class auto_ptr is a class template whose sole
template parameter is class T. You instantiate the template by specifying
some actual class for T and declaring some object of the resulting type:
auto_ptr<std::string> aps;
That gives you another actual class, "auto-pointer-to-string", which is
exactly like:
class auto_ptr_to_string
{
std::string * ptr;
public:
explicit auto_ptr(std::string * p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
std::string & operator*() {return *ptr;}
std::string * operator->() {return ptr;}
// ...
};
And aps is an object defined like that.
The class has a data member ptr, which is a pointer to an std::string.
The class also has an operator:
std::string & operator*() {return *ptr;}
This operator defines the behaviour that results from
applying the '*'-prefix to an object of type auto_ptr<std::string>,
e.g.*aps.
The definition of the operator tells you that it returns a reference to
an std::string, and that the std::string referred to by this reference is
*ptr, which means "the one referred to by the data member ptr".
So:
auto_ptr<std::string> aps(new std::string("Get it?"));
constructs an auto_ptr<std::string> called aps and the constuctor
initializes the data member aps.ptr with a pointer to a dynamically
allocated std::string containing "Get it?".
And:
std::string s = *aps;
according to the definition of auto_ptr<std::string>::operator*(),
declares an std::string s and initializes it with the std::string
referred to by aps.ptr, namely that one containing "Get it?"
Finally the class T syntax for template parameters does not actually
restrict their values to classes: auto_ptr<int>, for example, is fine,
though int is not a class type. And I reiterate Mike Seymour's comment
about auto_ptr being a bad old thing.

C++ compiler picking the wrong overload of a class member function

I have this code:
template <class T>
class Something
{
T val;
public:
inline Something() : val() {}
inline Something(T v) : val(v) {}
inline T& get() const { return val; }
inline Something& operator =(const Something& a) { val = a.val; return *this; }
};
typedef Something<int> IntSomething;
typedef Something<const int> ConstIntSomething;
class Other
{
public:
IntSomething some_function()
{
return IntSomething(42);
}
ConstIntSomething some_function() const
{
return ConstIntSomething(42);
}
};
void wtf_func()
{
Other o;
ConstIntSomething s;
s = o.some_function();
}
However, the compiler picks the wrong overload of Other::some_function() in wtf_func() (i.e. the non-const one). How can I fix this? Note that for certain reasons I cannot change the name of Other::some_function().
o is not const-qualified, so the non-const some_function is selected. If you want to select the const-qualified overload, you need to add the const qualifier to o:
Other o;
Other const& oref(o);
ConstIntSomething s;
s = oref.some_function();
When overload resolution occurs, the compiler only looks at the o.some_function() subexpression; it does not look at the context around the function call to decide to pick something else. Further, the return type of a member function is not considered during overload resolution.
Note that it may make more sense for IntSomething to be implicitly convertible to ConstIntSomething, either using an operator ConstIntSomething() overload in IntSomething (less good) or using a non-explicit ConstIntSomething(IntSomething const&) constructor in ConstIntSomething (more good).
It doesn't pick the wrong overload; const-ness is resolved by whether this is const or not. In your case, o is non-const, so the non-const overload is picked.
You can hack this by creating a const-reference to o, e.g.:
const Other &o2 = o;
s = o2.some_function();
But really, you should probably be considering your overloads in Something. For instance, you can't currently do this:
IntSomething x;
ConstIntSomething y;
y = x;
which doesn't sound correct. Why shouldn't you be allowed to take a const ref to a non-const ref?
Your object o needs to be const object for a const function to be called on it. Otherwise the compiler rightly picks up the non const version of the function.
The compiler picks the overload to use based on the constness of the object that will become this. You can make it call the desired version with static_cast: s = static_cast<const Other&>(o.some_function());
You might also want to copy the new behaviour found in the containers of the C++0x standard library. Containers such as vector now have members cbegin() and cend() that return a const_iterator whether the container is const or not unlike begin() and end()
class Other {
// Rest of other
public:
// No overload for non-const
// Even if called with a non const Other, since this member is marked
// const, this will be of type Other const * in all cases and will call
// the const qualified overload of some_function.
ConstIntSomething csome_function() const
{
return some_function();
}
};

const overloaded operator[] function and its invocation

I define two versions of overloaded operator[] function in a class array. ptr is a pointer to first element of the array object.
int& array::operator[] (int sub) {
return ptr[sub];
}
and
int array::operator[] (int sub) const {
return ptr[sub];
}
Now, if I define a const object integer1 the second function can only be called..... but if I make a non-const object and then invoke as below:
cout << "3rd value is" << integer1[2];
which function is called here?
In your second example, the non-const version will be called, because no conversion is required, and a call that requires no conversion is a better match than one that requires a conversion.
Ultimately, however, you have a basic problem here: what you really want is behavior that changes depending on whether you're using your object as an rvalue or an lvalue, and const doesn't really do that. To make it work correctly, you normally want to return a proxy object, and overload operator= and operator T for the proxy object:
template <class T>
class myarray {
T *ptr;
class proxy {
T &val;
proxy &operator=(proxy const &p); // assignment not allowed.
public:
proxy(T &t) : val(t) {}
operator T() const { return val; }
proxy &operator=(T const&t) { val = t; return *this; }
};
proxy const operator[](int sub) const { return proxy(ptr[sub]); }
proxy operator[](int sub) { return proxy(ptr[sub]); }
// obviously other stuff like ctors needed.
};
Now we get sane behavior -- when/if our array<int> (or whatever type) is const, our operator[] const will be used, and it'll give a const proxy. Since its assignment operators are not const, attempting to use them will fail (won't compile).
OTOH, if the original array<int> was not const, we'll get a non-const proxy, in which case we can use both operator T and operator=, and be able to both read and write the value in the array<int>.
Your const version should return const int& not int, so that the semantics are just the same between the two functions.
Once you've done that, it doesn't matter which one is used. If the const version has to be used because your object has a const context, then it will be... and it won't matter as you're not trying to modify anything. Otherwise, it'll use the non-const version... but with just the same effect.