Under which circumstances would you want to use code of this nature in c++?
void foo(type *&in) {...}
void fii() {
type *choochoo;
...
foo(choochoo);
}
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.
This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
50% of C++ programmers like to set their pointers to null after a delete:
template<typename T>
void moronic_delete(T*& p)
{
delete p;
p = nullptr;
}
Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL
int iSizeOfArray(int* &piArray) {
piArray = new int[iNumberOfElements];
...
return iNumberOfElements;
}
It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.
One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.
In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.
Another situation when you may need this is if you have stl collection of pointers and want to change
them using stl algorithm. Example of for_each in c++98.
struct Storage {
typedef std::list<Object*> ObjectList;
ObjectList objects;
void change() {
typedef void (*ChangeFunctionType)(Object*&);
std::for_each<ObjectList::iterator, ChangeFunctionType>
(objects.begin(), objects.end(), &Storage::changeObject);
}
static void changeObject(Object*& item) {
delete item;
item = 0;
if (someCondition) item = new Object();
}
};
Otherwise, if you use changeObject(Object* item) signature you have copy of pointer, not original one.
Refer the code below:
When we pass x as Node *x, a new variable is created with the same address passed on by the caller function.
If you modify the value pointed by the pointer, that change will be reflected in the caller function variable.
But if we change the value of the pointer itself it will not be reflected in the caller function because callee function has the copy of the passed pointer not the original pointer itself.
void increment(int *x) {
(*x)++;
x++;
cout << x << endl; // prints 0x7ffe9f8e1900
}
int main() {
int a = 10;
int *x = &a;
increment(x);
cout << *x << endl; // prints 11
cout << x << endl; // prints 0x7ffe9f8e18fc
return 0;
}
Now, check the below code:
When we pass x as Node *&x, we pass a reference of the original variable present in the caller function meaning these two variable (caller and callee root) are same, their name may differ.
if we modify the value pointer by the pointer, that change will be reflected in the caller function variable.
Now if we change the value of the pointer itself it will also be reflected in the caller function variable.
void increment(int* &x)
{
(*x) ++;
cout << *x << endl; // prints 11
x++;
cout << x << endl; // prints 0x7fffb93eba70
}
int main()
{
int a = 10;
int *x = &a;
increment(x);
cout << *x << endl; // prints garbage
cout << x << endl; // prints 0x7fffb93eba70
return 0;
}
Related
Under which circumstances would you want to use code of this nature in c++?
void foo(type *&in) {...}
void fii() {
type *choochoo;
...
foo(choochoo);
}
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.
This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
50% of C++ programmers like to set their pointers to null after a delete:
template<typename T>
void moronic_delete(T*& p)
{
delete p;
p = nullptr;
}
Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL
int iSizeOfArray(int* &piArray) {
piArray = new int[iNumberOfElements];
...
return iNumberOfElements;
}
It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.
One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.
In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.
Another situation when you may need this is if you have stl collection of pointers and want to change
them using stl algorithm. Example of for_each in c++98.
struct Storage {
typedef std::list<Object*> ObjectList;
ObjectList objects;
void change() {
typedef void (*ChangeFunctionType)(Object*&);
std::for_each<ObjectList::iterator, ChangeFunctionType>
(objects.begin(), objects.end(), &Storage::changeObject);
}
static void changeObject(Object*& item) {
delete item;
item = 0;
if (someCondition) item = new Object();
}
};
Otherwise, if you use changeObject(Object* item) signature you have copy of pointer, not original one.
Refer the code below:
When we pass x as Node *x, a new variable is created with the same address passed on by the caller function.
If you modify the value pointed by the pointer, that change will be reflected in the caller function variable.
But if we change the value of the pointer itself it will not be reflected in the caller function because callee function has the copy of the passed pointer not the original pointer itself.
void increment(int *x) {
(*x)++;
x++;
cout << x << endl; // prints 0x7ffe9f8e1900
}
int main() {
int a = 10;
int *x = &a;
increment(x);
cout << *x << endl; // prints 11
cout << x << endl; // prints 0x7ffe9f8e18fc
return 0;
}
Now, check the below code:
When we pass x as Node *&x, we pass a reference of the original variable present in the caller function meaning these two variable (caller and callee root) are same, their name may differ.
if we modify the value pointer by the pointer, that change will be reflected in the caller function variable.
Now if we change the value of the pointer itself it will also be reflected in the caller function variable.
void increment(int* &x)
{
(*x) ++;
cout << *x << endl; // prints 11
x++;
cout << x << endl; // prints 0x7fffb93eba70
}
int main()
{
int a = 10;
int *x = &a;
increment(x);
cout << *x << endl; // prints garbage
cout << x << endl; // prints 0x7fffb93eba70
return 0;
}
A class type called "Pair" has already been defined for you. You need to write a function called pairFactory that creates an instance of Pair on the heap. Do not create the object on the stack. Then, your function needs to return a pointer to that created object.
I have written the code for pairFactory. It seems to run, but I get an InfraError.
Please help me find my mistake.
Also, I need to create the object in heap memory.
#include <iostream>
// This class Pair has already been defined for you.
// (You may not change this definition.)
class Pair {
public:
int first, second;
void check() {
first = 5;
std::cout << "Congratulations! The check() method of the Pair class \n has executed. (But, this isn't enough to guarantee \n that your code is correct.)" << std::endl;
}
};
Pair *pairFactory() {
//
Pair P;
P.check();
// (You can use as many lines as you want.)
return &P;
}
// Your function should be able to satisfy the tests below. You should try
// some other things to convince yourself. If you have a bug in this problem,
// the usual symptom is that after you submit, the grader will crash with a
// system error. :-)
int main() {
Pair *p;
p = new pairFactory();
// This function call should work without crashing:
p->check();
// Deallocating the heap memory. (Assuming it was made on the heap!)
delete p;
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
return 0;
}
You've got it backwards. Your factory needs to allocate on the heap. What you're doing is returning the address of a function-local object that doesn't exist anymore.
Pair *pairFactory() {
return new Pair;
}
And then in your main function:
Pair *p = pairFactory();
You return reference to local variable here.
Pair *pairFactory() {
Pair P;
P.check();
return &P; // Dangling pointer
}
So you have dangling pointer, once you leave the function.
You have to call new.
Pair *pairFactory()
{
return new Pair{};
}
main may look like:
int main() {
Pair* p = pairFactory();
// This function call should work without crashing:
p->check();
// Deallocating the heap memory. (Assuming it was made on the heap!)
delete p;
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}
Better to use smart pointer to not have to manage memory yourself:
std::unique_ptr<Pair> pairFactory()
{
return std::make_unique<Pair>();
}
int main() {
auto p = pairFactory();
p->check();
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}
You did exactly as you were told not to do:
Pair *pairFactory() {
Pair P; // <----- creates an instance of Pair on the stack
…
}
The intention of this exercise likely was to test your knowledge on the new operator. See here https://en.cppreference.com/w/cpp/memory/new/operator_new
The function
Pair *pairFactory() {
return &P;
}
returns a pointer to memory on the local stack, which is destroyed / invalid as soon as it returns to main().
The issue with your code is that it returns a pointer that points to nothing as P only exists till the value of p is returned, as stored in heap memory. Using new keyword will allocate the memory in heap and will return a pointer to the value.
Pair *pairFactory() {
Pair P;
P.check();
return &P;
}
I've been making a tree, because planting a trees will save the planet (or just the program).
class Tree {
Node* root;
// ...
void insert(int value){
private_insert(value, root);
}
void insert_private(int value, node* n){
if(n == nullptr){
n = new node(value);
} else {
your standard recursive insertion function here
}
}
// ...
};
Long story short i've tried using shared_ptrs first, but the the insert() function will never add any element into my tree. I thought i might be doing something wrong with shareds so i tried raw pointers and i got the same non-inserty resoults.
Turns out i need to pass a reference my root/nodes.
void insert_private(int value, node*& n) {...};
I understand that if i dont pass something as reference then a copy is made. But if a pointer holds an address, doesnt it's copy hold the same address? if i make a new() to a non-referenced pointer why doesnt it stick to my root/nodes?
The why is my question here, i can accept it that it works like this, my tree works, but i dont know why its like this.
edit: After reading the comments i created this small expert level program:
void fn(int* i){
cout << "Address of local in fn before change: " << i << endl;
i = new int(2);
// so basically here we made a new int, and i will get the address of
// this integer and will point to there, what we passed on before
// becomes irrelevant
cout << "Address of local in fn after change: " << i << endl;
}
void fn2(int **i){
cout << "Address of local in fn2 before change: " << i << endl;
*i = new int(2);
cout << "Address of local in fn2 after change: " << i << endl;
}
int main(){
int* p = nullptr;
cout << "Address of p: " << p << endl;
fn(p);
cout << "p& is: " << &p << endl;
fn2(&p);
cin.get();
return 0;
};
Thank you, everyone, for the answers, it helped a lot. random.org will determine who's the one who will get the approved answer thing.
Yes it's a copy and it holds the same address, but you are assigning only to the copy which is then thrown away when the function returns. The original is unaltered. That's your problem.
As an aside, IMHO, if you are altering the value of a parameter, you should use a pointer, hence a pointer to a pointer in your case. It makes it much more obvious to the reader that you're changing the value.
n = new node(value); is an assignment.
The pointer gets a new value. Now it points to somewhere else. The pointer was passed by value, so the calling code won't see any change - the assignment only had a local effect.
In insert_node you are changing what n is pointing to.
If you want that to be reflected in the caller, then you need to pass the pointer n by reference: void insert_private(int value, node*& n), although I prefer node** n as that signals to the caller of the function that the parameter value might change.
Although, since root is a class member, you can modify it directly within insert_private.
But if a pointer holds an address, doesnt it's copy hold the same address?
Sure, until you change the address held in the copy.
Your design aside to the "why?": A pointer is a normal variable. Changes made to a local copy in the callee won't be reflected on the caller side.
void foo (int a)
{ // here: a is a copy of whatever will be passed to foo
a = 2;
}
void foo2 (int &a)
{ // here: a is something like 'a local name' for the int passed to foo2
a = 3;
}
int x = 0;
foo(x); // inside foo(x), a is another int copied from x
// x still 0 here
foo2(x); // inside foo2(x), a is 'a local name' for x
// x == 3 now
Pointers behave the same way as they're just variables containing an address.
void bar (int * a)
{
a = new int;
}
void bar2(int * &a)
{
a = new int;
}
int * x = nullptr;
bar(x); // inside bar(x), a is a new pointer copied from x
// x still nullptr here
// (and memory leaking from the new without delete)
bar2(x); // inside bar2(x), a is 'a name' for the passed pointer x
// x contains memory address from a new int
delete x;
// can be deleted -> no leak
Under which circumstances would you want to use code of this nature in c++?
void foo(type *&in) {...}
void fii() {
type *choochoo;
...
foo(choochoo);
}
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.
This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
50% of C++ programmers like to set their pointers to null after a delete:
template<typename T>
void moronic_delete(T*& p)
{
delete p;
p = nullptr;
}
Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL
int iSizeOfArray(int* &piArray) {
piArray = new int[iNumberOfElements];
...
return iNumberOfElements;
}
It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.
One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.
In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.
Another situation when you may need this is if you have stl collection of pointers and want to change
them using stl algorithm. Example of for_each in c++98.
struct Storage {
typedef std::list<Object*> ObjectList;
ObjectList objects;
void change() {
typedef void (*ChangeFunctionType)(Object*&);
std::for_each<ObjectList::iterator, ChangeFunctionType>
(objects.begin(), objects.end(), &Storage::changeObject);
}
static void changeObject(Object*& item) {
delete item;
item = 0;
if (someCondition) item = new Object();
}
};
Otherwise, if you use changeObject(Object* item) signature you have copy of pointer, not original one.
Refer the code below:
When we pass x as Node *x, a new variable is created with the same address passed on by the caller function.
If you modify the value pointed by the pointer, that change will be reflected in the caller function variable.
But if we change the value of the pointer itself it will not be reflected in the caller function because callee function has the copy of the passed pointer not the original pointer itself.
void increment(int *x) {
(*x)++;
x++;
cout << x << endl; // prints 0x7ffe9f8e1900
}
int main() {
int a = 10;
int *x = &a;
increment(x);
cout << *x << endl; // prints 11
cout << x << endl; // prints 0x7ffe9f8e18fc
return 0;
}
Now, check the below code:
When we pass x as Node *&x, we pass a reference of the original variable present in the caller function meaning these two variable (caller and callee root) are same, their name may differ.
if we modify the value pointer by the pointer, that change will be reflected in the caller function variable.
Now if we change the value of the pointer itself it will also be reflected in the caller function variable.
void increment(int* &x)
{
(*x) ++;
cout << *x << endl; // prints 11
x++;
cout << x << endl; // prints 0x7fffb93eba70
}
int main()
{
int a = 10;
int *x = &a;
increment(x);
cout << *x << endl; // prints garbage
cout << x << endl; // prints 0x7fffb93eba70
return 0;
}
If I have a list<object*>>* queue and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code):
object* objPtr = queue->first();
queue->pop_first();
return objPtr; // is this a pointer to a valid memory address now?
?
According to the documentation on http://www.cplusplus.com/reference/stl/list/pop_front/ it calls the destructor of the deleted element, but I'm confused as to whether it means the linked list's node object, or the actually stored "user" object.
Edit: I might be front instead of first, my bad.
Yes, it is a valid pointer. List will not release the memory allocated by you. List will destroy its internal not the user object.
Yes it's valid: Since you put pointers into the list, only the pointer gets destroyed, not the object itself.
Yes objPtr contains pointer to a valid memory.
When you insert an element into a std::list, list makes a copy of it. In your case the element is an address (a pointer) so list makes a copy of the address and stores it.
object * optr = queue->pop_front();
optr now points to the object
queue->pop_front();
removes the element (an address/pointer) from the list, optr already points to your object.
After you're done with the object don't forget do delete it otherwise you end up with memory leak.
Example:
#include <iostream>
#include <list>
using namespace std;
struct A
{
static int count;
A() : val(count++) { cout << "A(" << val << ")" << endl; }
~A() { cout << "~A(" << val << ")" << endl; }
int val;
};
int A::count = 0;
ostream& operator<<(ostream& os, A& a) { return os << a.val; }
int main()
{
list<A*> alist;
for (unsigned int i = 3; i; --i) alist.push_back(new A());
for (unsigned int i = 3; i; --i)
{
A * aptr = alist.front();
alist.pop_front();
cout << *aptr << endl;
delete aptr;
aptr = 0;
}
}
The standard indeed says (23.2.2.3/5) that the destructor of the element's type is called. But this type is a pointer here, and the destructor of a pointer does nothing...
Your code is well but it is better to use list< boost::shared_ptr<object> >.
shared_ptr < object> objPtr = queue->first();
queue->pop_first();
return objPtr;
When you remove the elements, STL containers will not destroy the user objects allocated on heap.
class A
{
};
list<A*> PointerToObjectList;
A* ptr = new A();
PointerToObjectList.push_back(ptr);
If you remove the ptr from the list, list will not delete the object automatically. You need to explicitly call delete once the object is no longer being used.