If a StoringClass needs a reference to a pointer, you must make sure that there is a pointer to which it refers (and modifies, since it is not a reference to a constant), with a lifespan until the link is specified.
#include <string> #include <iostream> template <typename T> class StoringClass { T& data; public: StoringClass (T& input): data(input) { } void print() const { std::cout << data << "\n"; } void set(T x) { data = x; } }; class RefPtrTest { const std::string test; const char *ptr; StoringClass<const char*> storingClass; public: RefPtrTest(): test("hello"), ptr(test.c_str()), storingClass(ptr) { } void print() const { storingClass.print(); } void set(const char* x) { storingClass.set(x); } }; int main() { RefPtrTest t; t.print(); t.set("world"); t.print(); }
Conclusion:
hello world
IMO StoringClass is a bit weird. For example, I could also mark the set const functions, and it will still work. But if you need to use it, you must use it. If you can use the StoringClass<const char *const> instead, this might be better: this ensures that you do not call any StoringClass functions that change the pointer. The way you asked a question suggests that you do not expect this to happen.
Edit:
If test not const, although RefPtrTest could have a function:
void set_another_way(const char *x) { test = x; set(test.c_str()); }
Which will change the line and update the pointer referenced by storingClass . The body of the function is equivalent to test = x; ptr = test.c_str(); test = x; ptr = test.c_str(); . Assuming a single-threaded code that also takes into account any doubts about the validity of the value of the pointer returned by test.c_str() , provided that set_another_way is the only means by which test ever changed.
Honestly, storingClass should not be called storingClass . He does not store anything; -p
source share