Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
I often use references to avoid unnecessary copying that comes with creating a new variable and assigning existing data to it.
Recently I was thinking about the example of a reference being assigned with an expression and whether there are really any advantages to using a reference for that. To give an example, let's say I have two vector object instances and I subtract one from the other. In the example below I am defining a new object instance to which the expression (subtraction) will be assigned to.
VectorClass vector1{// Instantiate with data};
VectorClass vector1{// Instantiate with data};
VectorClass vector3 = vector2 - vector1;
In my understanding, the expression will be evaluated, stored on the stack and copied to the new vector object (vector3).
What exactly does happen in the case of:
VectorClass vector1{// Instantiate with data};
VectorClass vector1{// Instantiate with data};
VectorClass& vector3 = vector2 - vector1;
My guess is that the expression will be evaluated, stored on the stack and the reference &vector3 references this memory, until they both go out of scope and get destroyed.
My question is: Am I correct, and if so, is the only advantage to the second example the fact that the copying when assigning value to vector3 doesn't happen?
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I am using a library that provides functions related to randomness (https://github.com/effolkronium/random#is-equal) and I applied one of them that will randomly choose between the 2 objects.
Class object1;
Class object2;
std::unique_ptr<Class> p1 = std::make_unique<Class>(Random::get({object1, object2}));
std::unique_ptr<Class> p2 = std::make_unique<Class>(Random::get({object1, object2}));
Because I am using unique_ptr is it certain that these two pointers will always point to a different object?
no matter what object is chosen (1 or 2) make_unique will call the copy constructor p1 will not point to object1 or object2 it will create a new object of type 'Class' and will point to that.
-> p1 and p2 will always point to different objects (of type 'Class')
after your lines, you have 4 different objects
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am still a beginner in c++, but I know something. I am studying the 1st term and I wanna make my own project, IMO it's the best way to learn to program. Anyway I wanna load data from file to dynamic array (and I know how to do that) but I to that job be done by special function and to that array be visible for other function (alternativity global). I know that using global variables is not good idea so I am thinking if it's possible to make variable friend with NO classes (bc I didn't use and learn classes yet)
Thanks in advance!
friend is not what you're looking for. A variable is just a named object. What you want to do here is not to somehow access the function's variable from the outside (that's not actually possible, function variables only exist when the function is executing). You want to transfer the object from one function to th other. That's done through the function's return value:
std::vector<int> readDataFromFile() {
std::vector<int> data;
// Read the file and store it into `data`
return data;
}
int main() {
std::vector<int> myData = readDataFromFile();
// Use `myData` as needed
}
You can see above that readDataFromFile works on its data variable, then returns it. This means that, right as readDataFromFile ends, myData in main (another, independent object) is initialized from data, and the data itself lives on.
Notes:
Do not use C-style arrays, new or delete. These are meant for compatibility with C and low-level memory management, not general use. A C++ dynamic array is an std::vector<YourType>.
Further notions:
Here myData is move-initialized, which means that no copy of the data is made: the dynamic array is transferred directly from data to myData
This is a case where NRVO can occur. That's an optimization which notices that data is redundant, and will replace it with direct access to myData, so there will only ever be one vector object throughout the program's execution. This is not observable in the general case., wo you don't need to worry about it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
int tenTimes(int n) {
return 10*n;
}
void tenTimesVector3(int vector[3]) {
vector[0] = tenTimes(vector[0]);
vector[1] = tenTimes(vector[1]);
vector[2] = tenTimes(vector[2]);
}
Here we are passing one element to the function but using that they are accessing all elements.
If you worry about the mutability of your buffer, then in general yes, it's not "safe" to pass a non-const reference to your buffer into a function. As you noted, the function can modify any array element.
If the function is const correct (it accepts a const reference or pointer), then you can be fairly certain it won't modify your array by accident. A compiler will catch any attempt at modification. Of course, the function can cast away the const and do nasty things, const here will offer some protection from Murphy, not from Machiavelli.
The only way to be absolutely positive a function won't modify your data is to not let it reference it. If you are genuinely concerned, you can just pass it a copy:
std::vector<int> data_we_want_to_keep(3);
// ...
std::vector<int> copy_of_data = data_we_want_to_keep;
tenTimesVector3(copy_of_data.data());
Now the function will not be able to modify data_we_want_to_keep itself, despite needing access to whatever values in that buffer.
Quite often though, code is written to be well behaved. If a function accepts a const reference or pointer to your data, you can be reasonably assured it will only read it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
given class (for example in name of X) , I want to allocate array like that:
X** array=new X*[20];
Let's look about the following function:
void Func(){
X** array=new X*[2];
X[0]=& X(5);
X[1]=& X(3);
}
Is it OK to do it like that or that I must to do it with new?
The thing is, when you do something like this :
X foo(5);
X[0] = &foo;
(wich i suppose is what you want to say)
X[0] will take the adress of foo, wich is a local variable who will only exist in the scope of your function. And if i do not tell bullshit, does not compile. (-fpermissive)
So after the last instruction of your function, the usage of this pointer will be Undefined
You can't be sure after any allocation that the content of your data is equal to nullptr (if not initialise yet). Initialisation syntax have way different behavior depending language, compiler, stars position etc (just kidding for the last one) so make sure to read the documentation about it.
However you can be sure to init something with null Value by using a zero-initialisation. Link here
If you don't want to dynamicly allocate your array of pointer make sure that those pointer still valid during the lifetime of your object
Another solution could be to dynamicly allocate them.
X[0] = new X(5);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hello I have three classes
AbstSoccerTeam
PlayersSoccerTeam
PlayersFieldPlayerStates
PlayerSoccerTeam is a child class of AbstSoccerTeam.
bool AlanSoccerTeam::isClosestTeamMemberToSupportingPlayer(FieldPlayer* plyr)
is a method in player soccer team.
i am trying to call that method in the PlayersFieldPlayerStates class with this
PlayersSoccerTeam* sTeam;
sTeam->isClosestTeamMemberToSupportingPlayer(player);
I can get this problem when i run it
uninitialized local variable 'sTeam' used
I dont know whats going on or why i am getting this error.
Any help is apprecitated greatly
Thanking You
The problem is you have created a pointer to a PlayersSoccerTeam but you have not actually created the object itself yet.
I would suggest doing this.
PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);
You could alternatively do this.
PlayersSoccerTeam* sTeam = new PlayersSoccerTeam()
sTeam->isClosestTeamMemberToSupportingPlayer(player);
As perhaps an interesting education experience create a constructor that prints something to stdout when it is run and then try doing these two options and yours to see what happens. A constructor will be run whenever a new object is created.
PlayersSoccerTeam* sTeam;
This line declares a pointer to a PlayersSoccerTeam and nothing else. All you get from this line is a pointer. It doesn't point anywhere in particular since you haven't initialized. There is no PlayersSoccerTeam anywhere to point to.
If you want an object of type PlayersSoccerTeam, then you just want:
PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);
Since you told us about your hierarchy, it's possible that you want to use your PlayersSoccerTeam polymorphically as a AbstSoccerTeam. In this case you would need to use either a pointer or reference. This could be done like so:
AbstSoccerTeam* sTeam = new PlayersSoccerTeam();
// ...
delete sTeam;
Note that this still declares just a pointer, but the expression new PlayersSoccerTeam also creates a PlayersSoccerTeam object for the pointer to point to. Note that it's perfectly fine to assign a pointer to a PlayersSoccerTeam to a pointer to its parent AbstSoccerTeam - this is polymorphism in action. If you do this, you must make sure you delete sTeam; later, otherwise the object will be leaked.
A safer way to handle the user of dynamically allocated objects is to use a smart pointer, which you could do like so:
std::unique_ptr<AbstSoccerTeam> sTeam(new PlayersSoccerTeam());
Now you will not have to delete it because the std::unique_ptr takes care of that for you.