I have a class which stores an array and I need to write a method to return a pointer to that array so that other objects can access/modify it.
In an old version of my program, I did that by defining the array in C style. I.e, having a private element bool* list and then allocating memory in the constructor (and liberating that in the destructor). The method then was very simple:
bool* MyClass::getList() {
return list;
}
Now, I have decided to rewrite the code and use std::vector<bool> instead of the classical array. The problem is that I have also modified the above method as:
bool* MyClass::getList() {
return &(list[0]);
}
which seems to be the standard way of converting a C++ vector to C array. However, I cannot compile my code, I get the following error:
error: taking address of temporary [-fpermissive]
error: cannot convert ‘std::vector<bool>::reference* {aka std::_Bit_reference*}’ to ‘bool*’ in return
Could anyone help me out with this and tell me what shall I do?
(I have also read that another alternative is to use list.data() as the pointer but this would work only with the newest version of C++ compilers. I am not sure if this is a good idea or not).
std::vector<bool>is a specialization ofstd::vector, which doesn't work quite like a normal vector. See e.g. this reference.bool*) as the interface for accessing the list. I just thought this would require least modifications on the other parts of the code).