what does this C++ code snippet do?
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
I'm not sure how it's related to a template creation. Can someone explain to me what this code does?
Thank you.
Here's the code.
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
If you actually get asked about this code, the first thing I'd do is complain about the if-clause. that 0 should be nullptr as so:
if (wLocalEntity != nullptr) {
mEntitySpeed = wLocalEntity->getSpeed();
}
Also, please tell me you know you shouldn't compress your code so tightly. Bugs hide when you shove all those operators together with no whitespace.
Now, let's look at line 1:
IEntity* wLocalEntity = const_cast<IEntity*>(BaseSimSystem::getEntityRef());
Clearly, wLocalEntity is a pointer to an IEntity. I hope you understood that.
The const_cast<> bit is ridiculous and possibly a bug. We don't know what BaseSimSystem::getEntityRef() returns, but I suspect it returns a const pointer, and now you're trying to assign that back to a non-const variable. The const_cast<> is getting rid of the constness.
The correct code is almost certainly:
const IEntity * wLocalEntity = BaseSimSystem::getEntityRef();
However, it's possible that IEntity has methods that aren't flag const that really should be, so you might have to do this because some other programmer didn't apply const when he should have.
So the const_cast<IEntity *> says "take the return value in those parenthesis and yes, I know they're not a non-const IEntity *, but don't warn me about it because supposedly I know what I'm doing.
How's that?
Related
I saw an answer for a c++ challenge that had you copy a certain part of a string x times.
std::string repeatString(int xTimes)
{
repeatString;(3); //What's happening here?
}
He seemed to have solved the challenge with this code and I'm guessing he solved it the wrong way but I'm still unsure what's happening.
original challenge:
https://edabit.com/challenge/vxpP4nnDhRr2Yc3Lo
original answer by Marcus_2008
repeatString; is an expression that does nothing useful. Same for (3);. Its the same as 3; and does literally nothing. After removing that unnecessary fluff, the function is
std::string repeatString(int) {
//What's happening here?
// - nothing at all
}
And this, not only does it not repeat a string, but it invokes undefined behavior when called, because it is declared to return a std::string but does not.
Even changing the line to repeatString(3); would leave us with the same issue while return repeatString(3); would result in infinite recursion.
It is not possible that this code solves the task. You must have misunderstood something, or the real code looks different.
this is more like an ethical question:
if i have the following code:
void changeInt(int& value)
{
value = 7;
}
and i do:
int number = 3;
changeInt(number);
number will have value 7
I know that when the new stack frame will be created for changeInt function, new variables will be created and &value will point to number.
My concern here is that the caller, if it's not paying attention , can be fooled by thinking that is passing by value which actually, on the function frame , a reference will be created.
I know he can look in the header files and it's a perfect legitimate expression but still I find it unethical a bit :)
i think this should be somehow marked and enforced by syntax. Like in C# where you have ref keyword.
What do you guys think ?
This is one of those things where references are less clear than pointers. However, using pointers may lead to something like this:
changeInt(NULL);
when they actually should have done:
changeInt(&number);
which is just as bad. If the function is as clearly named as this, it's hardly a mystery that it actually changes the value passed in.
Another solution is of course to do:
int calculateNewInt(/* may need some input */)
{
return 7;
}
now
int number = 3;
...
number = calculateNewInt();
is quite obviously (potentially) changing number.
But if the name of the function "sounds like it changes the input value", then it's definitely fair to change the value. If in doubt, read the documentatin. If you write code that has local variables that you don't want to alter, make them const.
const int number = 3;
changeInt(number); /* Makes an error */
(Of course, that means the number is not changeable elsewhere either).
I know he can look in the header files and it's a perfect legitimate expression but still I find it unethical a bit :)
I think that's perfectly normal and part of the language. Actually, this is one of the bad things of C and C++: you have to check the headers all the time when dealing with an unknown API, since when calling a function you don't pass by reference explicitly.
That's not the case for all system languages though. IIRC Rust makes it obligatory to pass references explicitly.
Is it possible to specify parameters to an pointer with something called & in C/C++?
Basically let's say I have a function:
int vba (unsigned long *a, unsigned long *b){.....}
Can I declare non-pointer values to the parameters using this mysterious & call?
I am reading this book and the author is using it to do so, but he doesn't declare what
it is, or what it is in general. I googled "& C++ call" and I didn't get any results.
So then he specifies a non ptr assignment using it in anothe function like so:
int vca ()
{
unsigned long c, d;
vba(&c, &d);
//etc ...
}
This is where I am confused, I don't know what just happened here, or what that call does, how did he assign a pointer to a non-pointer like that ... seems quite awesome though I never heard of it before. Anyone mind elaborating on what this is, or how it is possible?
Also when I put this into my code it says in the error log: "Intellisense: identifier "amp is undefined"? This is where I got really lost because the compiler highlights the amp call in blue, so how is it undefined?
That is just HTML encoding for the & character. The website you got this from clearly got something wrong. Hm, I just reread your question and noticed that you're talking about a book. Doesn't really change anything other than make the mistake even more appalling.
Anyway, replace the & with & and you'll be good to go.
I wrote little wrapper for XML Lite library to use it in my MFC project. Can I use this code?
CString GetValue()
{
const WCHAR* pwszValue = NULL;
UINT cwchValue = 0;
m_pReader->GetValue(&pwszValue, &cwchValue);
return CString(pwszValue);
}
Or shoud I use CString& parameter in GetValue method signature?
There's no need to return through a parameter, this should work.
If you're worried about efficiency, don't. Return value optimization will most likely occur in this case.
If you're thinking about efficiency, then turn on optimization and measure. And consider whether the difference, if any, matters to you. It's almost sure that the compiler will do return value optimization (RVO) here.
But as a general rule, use the coding practice that gives you more clear code, i.e. in this case the function result, which gives more concise, robust and readable calling code.
That said, it looks like you're leaking memory for the pwszValue, and the Hungarian notation prefix is not exactly readable and reduces clarity, so the code needs a bit of reworking even when you do the sensible thing and use the function result value.
CString& would be dead wrong, returns a reference to a temporary, your program would crash very quickly.
I'm trying to get the following line to compile, but i'm suffering from pointer confusion:
int test = _s->GetFruitManager()->GetFruits()[2].GetColour();
std::cout << test << std::endl;
where _s is a pointer to S, and GetFruitManager() returns a pointer to a FruitManager object, GetFruits() returns a std::vector<Fruit>* and i then want to be able to use the operator [] to acess a specific Fruit object and call the Fruit's GetColour() method.
I think at some point i need to dereference the vector* returned by GetFruits() but i can't figure out how.
Apologies if this is somewhat convoluted! i'm still quite new to the language, but would appreciate some help clearing this up. I did try to break it down into more digestible steps but was unable to get it to compile either way.
I've actually just decided not to use this code snippet anyway, but it's become a matter of curiosity so i'll still submit the question anyway :)
You need to do this:
(*(_s->GetFruitManager()->GetFruits()))[2].GetColour();
As an alternative to using the [] syntax, you can invoke .at():
int test = _s->GetFruitManager()->GetFruits()->at(2).GetColour();
The ugly edition:
int test = _s->GetFruitManager()->GetFruits()->operator[](2).GetColour();
Yes, you need to dereference the pointer returned by GetFruits():
int test = (*_s->GetFruitManager()->GetFruits())[2].GetColour();
FruitManager* temp_ptr = _s->GetFruitManager();
std::vector<Fruit>* ptr_vec = temp_ptr->GetFruits();
Fruit* f_obj_ptr = (*ptr_vec)[2];
int test = f_obj_ptr->GetColour();
Even though the correct answer has been posted, I would prefer a version like that cause it is more readable. And when you come back 2 days later, you can find a bug/do a fix much easier/faster.
Since no one mentioned it, there is also this alternative (which I personally like to use in gdb only):
int test = _s->GetFruitManager()->GetFruits()[0][2].GetColour();