I'm trying to extract a const pointer to part way through an array. I found it works fine when using a vector, but won't compile (VS 2008) when using a valarray. Can somebody explain what the problem is?
struct vector_test
{
std::vector<int> v;
const int *pointy(const int i) const
{
return &(v[i]); // Ok
}
};
struct valarray_test
{
std::valarray<int> v;
const int *pointy(const int i) const
{
return &(v[i]); // error C2102: '&' requires l-value
}
};
std::valarray<T>::operator [](std::size_t) returns a T&, which will work fine.
std::valarray<T>::operator [](std::size_t) const returns a T, which will be an rvalue and consequently cannot have its address taken.
Because valarray_test::pointy is itself const, valarray_test::v is treated as const and consequently the const overload of operator[] is called. Either make valarray_test::v mutable or make valarray_test::pointy non-const.
Related
I'm creating a type punning class View which takes a pointer to byte and adapts it to an array of T. The issue is that a non-const View can be constructed from a const byte*. I don't want to have separate, incompatible types like a View and ConstView. Maybe I could have a member bool readonly that gets set in the const byte* constructor and is checked for in the non-const operator[] overload, causing it to throw. Is there a better way to handle this?
using std::byte;
template <class T>
class View {
public:
typedef T __attribute__((may_alias)) value_type;
typedef value_type* pointer;
typedef const pointer const_pointer;
typedef value_type& reference;
typedef const reference const_reference;
View(byte* p)
: data { buffer }
{}
View(const byte* p)
: data { const_cast<byte*>(p) }
{}
reference operator[](int index) {
return reinterpret_cast<pointer>(data)[index];
}
const_reference operator[](int index) const {
return reinterpret_cast<const_pointer>(data)[index];
}
private:
byte* data;
};
We can actually do all of this checking at compile-time. You're using std::byte, so I assume you're on at least C++17, which means this is really straightforward (We can do a lot of these tricks with older C++ versions, but it involves more template trickery)
We can use static_assert to enable or disable functions depending on the input type. And we'll use is_const_v to check whether our T type is const or not.
template <class T>
class View {
public:
...
View(std::byte* p)
: data { p } {
static_assert(!std::is_const_v<T>);
}
View(const std::byte* p)
: data { const_cast<std::byte*>(p) } {
static_assert(std::is_const_v<T>);
}
reference operator[](int index) {
static_assert(!std::is_const_v<T>);
return reinterpret_cast<pointer>(data)[index];
}
const_reference operator[](int index) const {
return reinterpret_cast<const_pointer>(data)[index];
}
private:
std::byte* data;
};
static_assert is just like assert, except that it runs when the code is generated rather than when it's run. So we define two constructors. One takes an std::byte* and only exists when T is not constant. The other takes a const std::byte* and only exists when T is constant.
Likewise, we have two overloads for operator[]. The first overload returns a mutable reference but can only be used if T is non-const. The second returns a const reference can be used in general. We don't need any assertions for it. (The C++ standard library uses that idiom all over the place: One function returns a constant reference from a const this pointer and one returns a mutable reference, and C++'s overloading rules can handle it)
To use
View<int> x { new std::byte[1] };
View<const int> y { const_cast<const std::byte*>(new std::byte[1]) };
// All fine
x[0] = 100;
std::cout << x[0] << std::endl;
std::cout << y[0] << std::endl;
// Fails at compile time
// y[0] = 100;
return 0;
Also, you'll want to give Rule of Three/Five a thorough read at some point soon. You're taking a pointer as argument, so you need to understand how to manage that resource. You'll either need to (preferred) take a smart pointer rather than a raw one, or if you insist on the raw pointer then you need to write your own or delete the destructor, move and copy constructors, and move and copy assignment operators.
Let us say that p below has to be a pointer to const X. Then it is not possible to call find for a set of pointers to X with my special compare class. Is that a shortcoming of 'set' and 'find'? Is it safe to solve it with const_cast as I have done?
struct X{
std::string key;
X(std::string s): key(s) {}
};
struct compare {
bool operator() (const X* lhs, const X* rhs) const {
return lhs->key < rhs->key;
}
};
int main() {
std::set<X*,compare> m;
const X a("hello");
const X*p=&a;
std::set<X*,compare>::const_iterator it=m.find(const_cast<X*>(p));
}
This use of const_cast is safe, but any usage of const_cast is scary. const_cast is legal so long as you don't modify the object through the cast, which std::set::find does not do.
However, you don't need a const_cast here. If you make your comparator transparent, that opts into allowing find to search based on anything comparable to the key type. This is exactly what we want:
struct compare {
using is_transparent = void; // doesn't matter which type you use
bool operator() (const X* lhs, const X* rhs) const {
// You might want to consider using std::less<X*> to compare these.
// std::less<T*> can compare pointers which are not part of the
// same array, which is not allowed with just a simple less-than
// comparison.
return lhs->key < rhs->key;
}
};
Complete example: https://godbolt.org/z/NsZccs
I have the following code:
#include <map>
using namespace std;
struct A {};
map</*const*/ A *, int> data;
int get_attached_value(const A *p) {
return data.at(p);
}
void reset_all() {
for (const auto &p : data) *p.first = A();
}
My problem is that this code fails on a type error both when I comment and uncomment the const in the type of data. Is there any way I can solve this without using const_cast and without losing the const in get_attached_value?
The problem seems to be in the pointee type, which has to be the same in both pointer declarations (map key type and the get_attached_value's argument).
OP's code uses const A*, which is a pointer to a const instance of class A (an alternative spelling is A const *). Leaving this const in both map declaration and in get_attached_value' argument almost works, but reset_all does not allow you to assign a new value to *p.first, because the resulting type is A const& (which cannot be assigned into).
Removing both consts works as well, but OP wants to keep a const in get_attached_value.
One solution for OP's requirements, keeping as many consts as possible, seems to be to change the pointer type to a const pointer to a non-const instance of A. This will keep reset_all working, while allowing to use a const pointer in both map declaration and get_attached_value's argument:
#include <map>
using namespace std;
struct A {};
map<A * const, int> data;
int get_attached_value(A * const p) {
return data.at(p);
}
void reset_all() {
for (const auto &p : data)
*p.first = A();
}
Another possible solution, with map's key as non-const but the get_attached_value's parameter const, could use std::lower_bound with a custom comparator to replace the data.at() call:
#include <map>
#include <algorithm>
using namespace std;
struct A {};
map<A*, int> data;
int get_attached_value(A const * const p) {
auto it = std::lower_bound(data.begin(), data.end(), p,
[] (const std::pair<A* const, int>& a, A const* const b) {
return a.first < b;
}
);
return it->second;
}
void reset_all() {
for (const auto &p : data)
*p.first = A();
}
However, this solution will be significantly less efficient than one that would use map's native search functions - std::lower_bound uses linear search when input iterators are not random access.
To conclude, the most efficient solution in C++11 or lower would probably use a const pointer as the map's key, and a const_cast in the reset_all function.
A bit more reading about const notation and pointers can be found here.
I have a class which has a member of type std:vector
private:
std::vector<int> myVector;
I have created Get method to access myVector
1. const std::vector<int> GetMyVector() const;
2. const void GetMyVector(std::vector<int>& vec) const;
The implementations are as follows respectively:
1. const std::vector<int> MyClass::GetMyVector() const
{
return myVector;
}
2. const void MyClass::GetMyVector(std::vector<int>& vec) const
{
vec = myVector;
}
Which one of the two Get methods is better and why?
I'd prefer option 3:
const std::vector<int>& MyClass::GetMyVector() const
{
return myVector;
}
Your option 1 returned a copy of myVector. This returns a const (so read-only) reference to the class member.
Why return the vector at all?
int MyClass::GetItem(const size_t index) const
{
return myVector[index];
}
First of all you are exposing your implementation when you return a private member of a class from a member function, which usually is bad design. Take a look at #JoachimPileborg's solution for an example of how to avoid this.
If you want to return a copy then you should return by value.
If you want to return a reference to an object then return by reference. However, bear in mind that when the object is destructed you will end up with a dangling reference, e.g.
class Foo {
public:
std::vector<int>& getVec() {
return myVec;
}
private:
std::vector<int> myVec;
};
int main() {
Foo* f = new Foo();
std::vector<int>& myRef = f->getVec();
delete f;
std::cout << myRef.size(); // The demons come! Dangling reference!
}
Because of this, it is often the right thing to return a copy instead of a reference.
If you are returning an object by copy then there is no any sense to declare it as const. So instead of
const std::vector<int> MyClass::GetMyVector() const
{
return myVector;
}
I would write
std::vector<int> MyClass::GetMyVector() const
{
return myVector;
}
The second declaration is worst than the first one because it only confuses users. It is not clear whether the corresponding data member of the class is assigned to the parameter or this method makes some changes of the parameter without assigning the corresponding data member to the parameter.
So considering suggested variants by you I would choise declaration
std::vector<int> MyClass::GetMyVector() const
{
return myVector;
}
As a rule of thumb always try to return const reference of a class member .
So use const std::vector<int> & MyClass::GetMyVector() const
Whew, that was a long title.
Here's my problem. I've got a template class in C++ and I'm overloading the [] operator. I have both a const and a non-const version, with the non-const version returning by reference so that items in the class can be changed as so:
myobject[1] = myvalue;
This all works until I use a boolean as the template parameter. Here's a full example that shows the error:
#include <string>
#include <vector>
using namespace std;
template <class T>
class MyClass
{
private:
vector<T> _items;
public:
void add(T item)
{
_items.push_back(item);
}
const T operator[](int idx) const
{
return _items[idx];
}
T& operator[](int idx)
{
return _items[idx];
}
};
int main(int argc, char** argv)
{
MyClass<string> Test1; // Works
Test1.add("hi");
Test1.add("how are");
Test1[1] = "you?";
MyClass<int> Test2; // Also works
Test2.add(1);
Test2.add(2);
Test2[1] = 3;
MyClass<bool> Test3; // Works up until...
Test3.add(true);
Test3.add(true);
Test3[1] = false; // ...this point. :(
return 0;
}
The error is a compiler error and the message is:
error: invalid initialization of non-const reference of type ‘bool&’ from a temporary of type ‘std::_Bit_reference’
I've read up and found that STL uses some temporary data types, but I don't understand why it works with everything except a bool.
Any help on this would be appreciated.
Because vector<bool> is specialized in STL, and does not actually meet the requirements of a standard container.
Herb Sutter talks about it more in a GOTW article: http://www.gotw.ca/gotw/050.htm
A vector<bool> is not a real container. Your code is effectively trying to return a reference to a single bit, which is not allowed. If you change your container to a deque, I believe you'll get the behavior you expect.
A vector<bool> is not implemented like all other vectors, and does not work like them either. You are better off simply not using it, and not worrying if your code can't handle its many peculiarities - it is mostly considered to be A Bad Thing, foisted on us by some unthinking C++ Standard committee members.
Some monor changes to your class should fix it.
template <class T>
class MyClass
{
private:
vector<T> _items;
public:
// This works better if you pass by const reference.
// This allows the compiler to form temorary objects and pass them to the method.
void add(T const& item)
{
_items.push_back(item);
}
// For the const version of operator[] you were returning by value.
// Normally I would have returned by const ref.
// In normal situations the result of operator[] is T& or T const&
// But in the case of vector<bool> it is special
// (because apparently we want to pack a bool vector)
// But technically the return type from vector is `reference` (not T&)
// so it you use that it should compensate for the odd behavior of vector<bool>
// Of course const version is `const_reference`
typename vector<T>::const_reference operator[](int idx) const
{
return _items[idx];
}
typename vector<T>::reference operator[](int idx)
{
return _items[idx];
}
};
As the other answers point out, a specialization is provided to optimize for space allocation in the case of vector< bool>.
However you can still make your code valid if you make use of vector::reference instead of T&. In fact it is a good practice to use container::reference when referencing data held by a STL container.
T& operator[](int idx)
becomes
typename vector<T>::reference operator[](int idx)
Of course ther is also a typedef for const reference:
const T operator[](int idx) const
and this one becomes (removing the useless extra copy)
typename vector<T>::const_reference operator[](int idx) const
The reason for the error is that vector<bool> is specialized to pack the boolean values stored within and vector<bool>::operator[] returns some sort of proxy that lets you access the value.
I don't think a solution would be to return the same type as vector<bool>::operator[] because then you'd be just copying over the regrettable special behavior to your container.
If you want to keep using vector as the underlying type, I believe the bool problem could be patched up by using a vector<MyBool> instead when MyClass is instantiated with bool.
It might look like this:
#include <string>
#include <vector>
using namespace std;
namespace detail
{
struct FixForBool
{
bool value;
FixForBool(bool b): value(b) {}
operator bool&() { return value; }
operator const bool& () const { return value; }
};
template <class T>
struct FixForValueTypeSelection
{
typedef T type;
};
template <>
struct FixForValueTypeSelection<bool>
{
typedef FixForBool type;
};
}
template <class T>
class MyClass
{
private:
vector<typename detail::FixForValueTypeSelection<T>::type> _items;
public:
void add(T item)
{
_items.push_back(item);
}
const T operator[](int idx) const
{
return _items[idx];
}
T& operator[](int idx)
{
return _items[idx];
}
};
int main(int argc, char** argv)
{
MyClass<string> Test1; // Works
Test1.add("hi");
Test1.add("how are");
Test1[1] = "you?";
MyClass<int> Test2; // Also works
Test2.add(1);
Test2.add(2);
Test2[1] = 3;
MyClass<bool> Test3; // Works up until...
Test3.add(true);
Test3.add(true);
Test3[1] = false; // ...this point. :(
return 0;
}