The lifetime of stack-allocated class members

Hi,

I would like to have class member objects that are not pointers, and be able to initialize them at some point after the container is created. Is this safe to do, or am I risking corrupted data due to std::string("theString value") being allocated on the stack instead of with new?

1
2
3
4
5
6
7
8
9
10
11
class MyObject {
public:
	std::string theString; // <- Stack-allocated member, not pointer
	MyObject() {
		init();
		// Is 'theString' member safe to use here (and beyond) as long as this 'MyObject' instance remains in scope?
	}
	void init() {
		theString = std::string("theString value"); // <- Function-local allocation on the stack, is this going to be bad?
	}
};

I appreciate any clarification on this. My Google searching keeps turning up details about pointers, or more simple scenarios that don't seem to apply directly. Thanks!
Last edited on
closed account (E0p9LyTq)
Your std::string object created on line 3 is created on the stack, but the underlying data MAY BE located on the heap. std::string's implementation handles all the char pointer details for you.

https://stackoverflow.com/questions/42049778/where-is-a-stdstring-allocated-in-memory
Thanks FurryGuy for your reply.

I've read that stack-allocated objects die naturally when they go out of scope. But most Google searches lead to more basic scenarios. Here I'm creating a std::string on the stack at line 9 and assigning it to my class member variable. So it seems like I could be making my class member value go out of scope as soon as init() returns. I was wondering if that's true or not.

But based on what you said, it got me thinking about how the class-level 'theString' must be working, and I eventually remembered that the '=' operator is overloaded. So my class-level variable is not going to be assigned to a soon-to-be-deallocated value. The stack-allocated string goes out of scope after line 9 as I suspected, but it first stores its c_str value into my class member's value (via operator=), which obviously lives as long as the 'MyObject' instance does. So 'theString' will be perfectly healthy and trustworthy. That's what I needed to confirm.

Thanks again!
closed account (E0p9LyTq)
As long as your object is alive and in scope, then any member data is. No matter where said member data is allocated.

That is one of the advantages of OOP. You don't have to deal with the messy details of data management across the lifetime of your object, as long as you properly do the grunt work in your ctor(s) and dstor(s).

Using a STL object for member data is even less work.
Topic archived. No new replies allowed.