B
Bob Altman
Hi all,
I have a basic question regarding holding references to objects in unmanaged
C++. Suppose my unmanaged C++ class has a method that accepts a reference
to an object as an argument, and stores the object reference in a stack
object, and another method that uses the stored objects in the stack object,
like this:
void MyClass::AcceptString(const string& myArg) {
m_myStack.push(myArg); // declared as stack<string> m_myStack
}
void MyClass:oSomething() {
string& s = m_myStack.Top();
<Do something with s>
}
Now, suppose this method is called with code that looks like this:
MyClass t;
t.AcceptString("Some text");
t.DoSomething();
As I understand things, the compiler creates a temporary string object
containing "Some text" and passes it to my method. My question is, what is
the lifetime of that temporary string object? I assume that nothing in C++
does reference counting or anything like that to keep my private reference
"alive". Since my method has grabbed a reference to the string, I assume
that I'm at risk of trying to access it after the caller to my method has
deallocated it. Is this all correct? To be safe, do I need to store a copy
of the string in the stack object, even though 99.9% of the time the caller
will not destroy the string while I'm using it?
I have a basic question regarding holding references to objects in unmanaged
C++. Suppose my unmanaged C++ class has a method that accepts a reference
to an object as an argument, and stores the object reference in a stack
object, and another method that uses the stored objects in the stack object,
like this:
void MyClass::AcceptString(const string& myArg) {
m_myStack.push(myArg); // declared as stack<string> m_myStack
}
void MyClass:oSomething() {
string& s = m_myStack.Top();
<Do something with s>
}
Now, suppose this method is called with code that looks like this:
MyClass t;
t.AcceptString("Some text");
t.DoSomething();
As I understand things, the compiler creates a temporary string object
containing "Some text" and passes it to my method. My question is, what is
the lifetime of that temporary string object? I assume that nothing in C++
does reference counting or anything like that to keep my private reference
"alive". Since my method has grabbed a reference to the string, I assume
that I'm at risk of trying to access it after the caller to my method has
deallocated it. Is this all correct? To be safe, do I need to store a copy
of the string in the stack object, even though 99.9% of the time the caller
will not destroy the string while I'm using it?