Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a pointer temporary to a reference

Tags:

c++

Please refer to the code below. In this code I am storing the const char* returned by test.c_str() into a reference. My question is - Will the data be correctly refering to the contents of test? I am thinking that the ptr returned by test.c_str() will be a temporary and if I bind it to a reference that reference will not be valid.

Is my thinking correct?

class RefPtrTest
{
    std::string test;
    StoringClass storingClass;
public: 
    RefPtrTest(): test("hello"), storingClass(test.c_str())
    {
    }
}

where StoringClass is

class StoringClass 
{
    const char*& data;
public: 
    StoringClass (const char*& input): data(input)
    {
    }
}

EDIT1: Let's just not consider what std::string is doing. Suppose I am using my own class called mystring

class RefPtrTest
{
    const mystring test;
    StoringClass storingClass;
public: 
    RefPtrTest(): test("hello"), storingClass(test.getInternalPointer())
    {
    }
}

getInternalPointer directly returns the internal pointer. I want to verify this hypothesis, while storingClass(test.getInternalPointer()) ptr returned by test.getInternalPointer() will be a temporary and if I bind it to a reference that reference will not be valid. Is my thinking correct?

EDIT2: That StoringClass is not under my control. Basically it's a template class where it stores reference to the type. I am using it for const char*. I am aware of all the design issues which you have raised. But I can't change that class, and I have to use it for const char *. there is no other way around it.

like image 355
Yogesh Arora Avatar asked Feb 28 '23 06:02

Yogesh Arora


2 Answers

The standard has the following to say about c_str (21.3.6/2)

Requires: The program shall not alter any of the values stored in the array. Nor shall the program treat the returned value as a valid pointer value after any subsequent call to a non-const member function of the class basic_string that designates the same object as this.

So the answer is no, you can not treat the pointer as a reference to the contents of the string (after any non const function calls on the string).

like image 183
Andreas Brinck Avatar answered Mar 07 '23 20:03

Andreas Brinck


Yes, your thinking is correct (test.c_str() returns a temp, so you can't use it to initialize a reference), unless test.c_str() actually returns a reference to a pointer, which I don't think it does... does it?

This should give you a compile error, though, did you try it?

In this particular case, actually using the pointer for something would not make much sense. But if you're only asking about references to pointers, then you're correct (regardless of type).

like image 38
falstro Avatar answered Mar 07 '23 20:03

falstro