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).
Thanks,