I am trying to get the hang of C++ pointers and objects, through a small project implementing a simple Vehicle Routing Problem. Even though my code is currently working, I can't shake the feeling that my approach is completely wrong. What bugs me, are snippets of code such as :
std::map<const Route*, double>::iterator it = quantities.begin();
if ((*(*(it->first)).getDestination()).getDemand() > (*(*(it->first)).getDeparture()).getSupply())
The pointer hell situation in the if condition is the result of the get methods returning pointers to already created objects. The methods being called are :
const Departure* Route::getDeparture() const {
return departure;
};
const Destination* Route::getDestination() const {
return destination;
};
and
int Destination::getDemand() const {
return demand;
};
int Departure::getSupply() const {
return supply;
};
Am I completely off track here, am i missing something or is this type of situtation something normal?
To increase readability you can change *s to ->:
if(it->first->getDestination()->getDemand() > it->first->getDeparture()->getSupply())
Also, if you aren't going to give up ownership of that object (and you aren't, in this case) it is better to return by const reference:
const Departure& Route::getDeparture() const {
return *departure;
};
and use ., not ->:
if(it->first->getDestination().getDemand() > it->first->getDeparture().getSupply())
instead of (*p).x write p->x.
Related
Basically Im wanting to fetch a pointer of a constant and anonymous object, such as an instance of a class, array or struct that is inialised with T {x, y, z...}. Sorry for my poor skills in wording.
The basic code that Im trying to write is as follows:
//Clunky, Im sure there is an inbuilt class that can replace this, any information would be a nice addition
template<class T> class TerminatedArray {
public:
T* children;
int length;
TerminatedArray(const T* children) {
this->children = children;
length = 0;
while ((unsigned long)&children[length] != 0)
length++;
}
TerminatedArray() {
length = 0;
while ((unsigned long)&children[length] != 0)
length++;
}
const T get(int i) {
if (i < 0 || i >= length)
return 0;
return children[i];
}
};
const TerminatedArray<const int> i = (const TerminatedArray<const int>){(const int[]){1,2,3,4,5,6,0}};
class Settings {
public:
struct Option {
const char* name;
};
struct Directory {
const char* name;
TerminatedArray<const int> const children;
};
const Directory* baseDir;
const TerminatedArray<const Option>* options;
Settings(const Directory* _baseDir, const TerminatedArray<const Option> *_options);
};
//in some init method's:
Settings s = Settings(
&(const Settings::Directory){
"Clock",
(const TerminatedArray<const int>){(const int[]){1,2,0}}
},
&(const TerminatedArray<const Settings::Option>){(const Settings::Option[]){
{"testFoo"},
{"foofoo"},
0
}}
);
The code that I refer to is at the very bottom, the definition of s. I seem to be able to initialize a constant array of integers, but when applying the same technique to classes, it fails with:
error: taking address of temporary [-fpermissive]
I don't even know if C++ supports such things, I want to avoid having to have separate const definitions dirtying and splitting up the code, and instead have them clean and anonymous.
The reason for wanting all these definitions as constants is that Im working on an Arduino project that requires efficient balancing of SRAM to Flash. And I have a lot of Flash to my disposal.
My question is this. How can I declare a constant anonymous class/struct using aggregate initialization?
The direct (and better) equivalent to TerminatedArray is std::initializer_list:
class Settings {
public:
struct Option {
const char* name;
};
struct Directory {
const char* name;
std::initializer_list<const int> const children;
};
const Directory* baseDir;
const std::initializer_list<const Option>* options;
Settings(const Directory& _baseDir, const std::initializer_list<const Option>& _options);
};
//in some init method's:
Settings s = Settings(
{
"Clock",
{1,2,0}
},
{
{"testFoo"},
{"foofoo"}
}
);
https://godbolt.org/z/8t7j0f
However, this will almost certainly have lifetime issues (which the compiler tried to warn you about with "taking address of temporary"). If you want to store a (non-owning) pointer (or reference) then somebody else should have ownership of the object. But when initializing with temporary objects like this, nobody else does. The temporaries die at the end of the full expression, so your stored pointers now point to dead objects. Fixing this is a different matter (possibly making your requirements conflicting).
Somewhat relatedly, I'm not sure whether storing a std::initializer_list as class member is a good idea might. But it's certainly the thing you can use as function parameter to make aggregate initialization nicer.
&children[length] != 0 is still true or UB.
If you don't want to allocate memory, you might take reference to existing array:
class Settings {
public:
struct Option {
const char* name;
};
struct Directory {
const char* name;
std::span<const int> const children;
};
const Directory baseDir;
const std::span<const Option> options;
Settings(Directory baseDir, span<const Option> options);
};
//in some method:
const std::array<int, 3> ints{{1,2,0}};
const std::array<Settings::Option> options{{"testFoo"}, {"foofoo"}};
Settings s{"Clock", {ints}}, options};
First, you're not aggregate-initializing anything. This is uniform initialization and you're calling constructors instead of directly initializing members. This is because your classes have user-defined constructors, and classes with constructors can't be aggregate-initialized.
Second, you're not really able to "initialize a constant array of integers". It merely compiles. Trying to run it gives undefined behavior - in my case, trying to construct i goes into an infinite search for element value 0.
In C++, there's values on the stack, there's values on the heap and there's temporary values (I genuinely apologize to anyone who knows C++ for this statement).
Values on the heap have permanent addresses which you can pass around freely.
Values on the stack have temporary addresses which are valid until
the end of the block.
Temporary values either don't have addresses
(as your compiler warns you) or have a valid address for the duration
of the expression they're used for.
You're using such a temporary to initialize i, and trying to store and use the address of a temporary. This is an error and to fix it you can create your "temporary" array on the stack if you don't plan to use i outside of the block where your array will be.
Or you can create your array on the heap, use its address to initialize i, and remember to explicitly delete your array when you're done with it.
I recommend reading https://isocpp.org/faq and getting familiar with lifetime of variables and memory management before attempting to fix this code. It should give you a much better idea of what you need to do to make your code do what you want it to do.
Best of luck.
This is in relation to an earlier question I had. I haven't managed to solve the problem there but for now I'm just trying to get better acquainted with the code to figure out how to deal with that problem.
Towards that goal, I've got around to trying out the suggestions given in that question and I'm a little stumped as to why the following isn't working.
in the header I have
class A {
public:
typedef std::multimap<int, double> intdoublemap_t;
const intdoublemap_t& getMap() const;
void setkey(int k);
void setvalue(double v);
void insertIntoMap();
intdoublemap_t mMapA;
private:
int key;
double value;
};
class B {
public:
typedef std::multimap<int, double> intdoublemap_t;
void mapValues(const A& a);
private:
intdoublemap_t mMapB;
};
in the implementation I have
const A::intdoublemap_t& A::getMap() const { return mMapA; }
void A::setkey(int k) { key = k; }
void A::setvalue(double v) { value = v; }
void A::insertIntoMap(){mMapA.insert(std::make_pair(key, value));}
void B::mapValues(const A & a){ const A::intdoublemap_t& mref = a.getMap();
mMapB = mref; }
and in main()
A a;
a.setkey(10);
a.setvalue(1232.2);
a.insertIntoMap();
B b;
b.mapValues(a);
The code compiles fine and everything to do with a works as expected but the map is not passing to b at all. It stays empty
Can anyone tell me why?
edit: I took another look at this and saw how to do it. I knew it was something stupidly basic. I just had to set mref in the function to a map in B and then could call a function to work on that map within B.
As #FrancoisAndrieux notes, your getMap() only sets a reference local to the function - not the class' intdoublemap_t mref. If you want the latter to be a reference to a map elsewhere, you have three options:
Make it intdoublemap_t& mref, initialize it on construction of the B instance.
Make it std::reference_wrapper<intdoublemap_t> mref, set it whenever you want (e.g. in mapValues().
Make it intdoublemap_t* (or std::shared_ptr<intdoublemap_t> in both A and B), set it whenever you like.
Note: As #FrancoisAndrieux says in a comment, with the second and third option (and without std::shared_ptr) you will have to be careful not to allow the reference to be used after the original object's lifetime has expired.
Having said all the above - I must also say that your design seems rather off to me. You should really not be doing any of these things and I'm 99% sure you're approaching your task the wrong way.
What's the best course of action in C++ to take in the following situation?
My class has some double pointer as a private member:
class A
{
private:
int** data;
//...//
public:
int** get_data () const { return data; };
//...//
}
And sometimes I'd like to check the values inside this pointer and change them. And there's some get function get_data for this purpose:
A* obj = new A();
//...//
int** data_from_A = obj->get_data();
// some manipulations with data_from_A pointer
But what if I want to be confident that nothing won't change it in the further usage?
How is it better to get only the "read access" to the data pointer?
Of course, we can make the data pointer public, but in this case it can be changed from the outside, that is unacceptable...
Thanks!
In C++, raw pointers, and especially pointer arithmetics, should only be used buried deep deep within a class that utilizes them for high performance computing.
The only reason to give something like a pointer to an array to the outside is that you use some other code that would be tedious to rewrite, like a highly optimized solver written by somebody who is used to writing C style code (with the solver actually being in C maybe).
If not, go with a class from the standard library, like std::vector (dynamic), std::array (static) or std::list (linked).
This would transform your code to something like
private:
vector<vector<int> > data;
public:
const vector<vector<int> >& get_data() const { return data; }
Simple as that, one const totally suffices, none more required for sub-vectors as it would be with a raw array.
Another way would be to go with
const int& get_data(const size_t i, const size_t j) const { return data[i][j]; }
which would work even with your current code.
For the vector, remember that if you want to use it for a while, then you have to get it with
const vector<vector<int> >& data = myClass.get_data();
and not with either of those
vector<vector<int> >& data = myClass.get_data(); //compile error
vector<vector<int> > data = myClass.get_data(); //works but unnecessarily copies the data
The answer is to make "data" private and make the function which sets it up a "friend". Then the member is protected from access, except within your special function.
However friend functions are usually a sign of poor design, so you will probably want to look at refactoring to eliminate the need for this.
Suppose the following:
struct C {
... // lots of other stuff
int get(int key) const { return m.at(key); } // This will never throw
private:
std::unordered_map<int, int> m;
};
Due to how the application works, I know that get never throws. I want to make get as fast as possible. So, I would like to make the access unchecked, i.e. I would like to write something like return m[key]. Of course, I cannot write exactly that while keeping get const. However, I want to keep get const, since it is logically const.
Here is the only (ugly) solution I came up with:
struct C {
... // lots of other stuff
int get(int key) const { return const_cast<C *>(this)->m[key]; }
private:
std::unordered_map<int, int> m;
};
Is there a better way?
One approach would be to use std::unordered_map::find:
struct C {
... // lots of other stuff
int get(int key) const { return m.find(key)->second; }
private:
std::unordered_map<int, int> m;
};
I object to the very reasoning behind this question. The overhead (of map.at() vs map[]) associated with catching an error due to unknown key is presumably tiny compared to the cost of finding the key in the first place.
Yet, you willingly take the serious risk of a run-time error just for such a marginal efficiency advantage that you presumably have not even validated/measured. You may think that you know that key is always contained in the map, but perhaps future code changes (including bugs introduced by others) may change that?
If you really know, then you should use
map.find(key)->second;
which makes the bug explicit if the iterator returned is invalid (i.e. equal to map.end()). You may use assert in pre-production code, i.e.
auto it = map.find(key);
assert(it!=map.end());
return it->second;
which in production code (when assert is an empty macro) is removed.
I'm having some trouble in declaring a STL Set of pointers to class instances. More specifically, I have this scenario:
class SimulatedDiskFile {
private:
// ...
public:
// ...
struct comparator {
bool operator () (SimulatedDiskFile* const& file_1, SimulatedDiskFile* const& file_2) {
return ((*file_1)->getFileName() < (*file_2)->getFileName());
}
};
}
typedef set<SimulatedDiskFile*, SimulatedDiskFile::comparator> FileSet;
The code above is not working. Compiler says it didn't find a member SimulatedDiskFile::comparator() function. If I put the function with this declaration (outside the struct), compiler says it was expecting a type.
Now here com my doubts (not only one, but related, I guess):
What is the the correct declaration for a set of pointers?
What is the correct declaration for a comparison funcion that compares pointers?
I did look up in many places before posting, but I found the references confusing and not quite related to my special case (as stupidly trivial as I think it is - actually, maybe this is the cause). So, any good links are of great help too!
Thanks in advance!
Fixing a few glitches,
#include <set>
class SimulatedDiskFile {
public:
int getFileName() { return 23; }
struct comparator {
bool operator () (SimulatedDiskFile* file_1, SimulatedDiskFile* file_2) {
return (file_1->getFileName() < file_2->getFileName());
}
};
};
typedef std::set<SimulatedDiskFile*, SimulatedDiskFile::comparator> FileSet;
compiles just fine.
Since you aren't showing where the 'getFileName()' method is supposed to be, I'm just going to go out on a limb and assume that you don't mean to double-dereference your pointers in the comparator. ie, you should do either:
return (file_1->getFileName() < file_2->getFileName());
or:
return ((*file_1).getFileName() < (*file_2).getFileName());
but not both.