Exception thrown using references, but it's fine with pointers

Hi.

Here is a function that returns a list starting from a tree using the InOrder traversal method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<typename type>
std::list<type> tree<type>::to_list()
{
    std::list<type> converted{};
    to_list_private(root, converted);
    return converted;
}

template<typename type>
std::list<type> tree<type>::to_list_private(tree_node<type>* current, std::list<type>& the_list)
{
    if (!current)
       return the_list;
	
    to_list_private(current->left, the_list);
    the_list.push_back(current->info);
    to_list_private(current->right, the_list);	
}


This code makes the program crash in the function to_list() the line before return converted; with the error "Access violation reading location"

However, if I change this code and use pointers instead, the program works fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<typename type>
std::list<type> tree<type>::to_list()
{
	std::list<type>* converted = new std::list<type>{};
	to_list_private(root, converted);
	return *converted;
}

template<typename type>
std::list<type>* tree<type>::to_list_private(tree_node<type>* current, std::list<type>* the_list)
{
    if (!current)
        return the_list;
	
    to_list_private(current->left, the_list);
    the_list->push_back(current->info);
    to_list_private(current->right, the_list);	
}



I can't figure out for what reason changing reference to pointer makes the difference.
Is there a dangling reference somewhere I'm unable to spot?

Thanks in advance!
Last edited on
One obvious problem is that to_list_private shouldn't return anything (i.e., it should be void).
on to_list_private()
«warning: control may reach end of non-void function»
Both of you are right: the function should return nothing.

BUT! I still don't get why using references is a problem whereas using pointers is fine.

In the first code snipped the reference parameter 'theList' is filled with 'converted'.

I don't see why the exception says "access violation reading location"
Last edited on
you are invoking undefined behaviour.
your foot is bleeding because you shot at it.

1
2
3
4
5
6
7
#include <list>
std::list<int> foo(){
}

int main(){
   std::list<int> asdf = foo();
}
¿how is `asdf' being constructed? ¿how is it destroyed? ¿what does happen at line 3?
now compare those operations on a pointer.
Topic archived. No new replies allowed.