2

Sorry for the confusing title, but I have absolutely no idea what is going on here. I'm making a generic tree struct in C++, but some of my values are overwriting others, but in a very specific way that I don't know how to search for. node.h is at the bottom of the question for reference.

This code in main.cpp:

#include <iostream>
#include <string>

#include "node.h"

int main() {
    Node<std::string> a("a");
    std::cout << a.value << '\n';

    Node<std::string> b("b");
    std::cout << a.value << '\n';

    Node<std::string> c("c");
    std::cout << a.value << '\n';

    Node<std::string> d("d");
    std::cout << a.value << '\n';

    return 0;
}

prints:

a
a
a
d

However, removing the two lines before the return prints:

a
a
c

The node.h file:

#ifndef NODE
#define NODE

#include <vector>

template <class T>
struct Node {
    Node(const T& value);

    const T& value;
    std::vector<const Node<T>*> children;
};

template <class T>
Node<T>::Node(const T& value): value(value) {}

#endif

I have no idea what's happening here. Apologies if this is a duplicate, but I have absolutely no idea how to look up this problem.

Alex F
  • 239
  • 1
  • 7
  • 2
    Member `value` should be `std::string`, not `const std::string&`. You're trying (and failing) to lengthen the life of a temporary beyond the constructor to which it was passed, and that doesn't work. [See this question](https://stackoverflow.com/questions/2784262/does-a-const-reference-class-member-prolong-the-life-of-a-temporary). – WhozCraig Sep 16 '19 at 05:26
  • Thank you both for your quick replies, that fixed my issue. – Alex F Sep 16 '19 at 05:28

0 Answers0