Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3875368
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T22:15:33+00:00 2026-05-19T22:15:33+00:00

Do class objects declared on the stack have the same lifetime as other stack

  • 0

Do class objects declared on the stack have the same lifetime as other stack variables?

I have this code:

#include <stdio.h>
#include <vector>
using std::vector;
#include <string>
using std::string;

class Child;
class Parent
{
public:
    Parent(string s) : name(s) { };
    vector<Child> children;
    string name;
};
class Child
{
public:
    Child() { /* I need this for serialization */ };
    Child(Parent *p) : parent(p) { };
    Parent *parent;
};

Parent
family()
{
    Parent p("John Doe");
    int i;
    printf("family:\n\tparent: 0x%x\n\ti: %x\n", &p, &i);
    for (i = 0; i < 2; ++i)
        p.children.push_back(Child(&p));
    return p;
}

int
main(void)
{
    Parent p = family();
    printf("main:\n\tparent: 0x%x\n", &p);
    for (unsigned int i = 0; i < p.children.size(); ++i)
        printf
        (
            "\t\tchild[%d]: parent: 0x%x parent.name '%s'\n", 
            i, 
            p.children[i].parent,
            p.children[i].parent->name.c_str()
        ); 
    return 0;
}

My questions:

  • In function family, is Parent p declared on the stack? From looking at the output, it would seem so
  • Each created Child goes on the stack too, right?
  • When I create each Child instance, I pass it a pointer to a stack variable. I imagine this is a big no-no, because stack variables are guaranteed to live only until the end of the function. After that the stack should get popped and the variables will be destroyed. Is this correct?
  • vector.push_back() passes arguments by reference, so at the end of the family function, p.children just contains references to the local variables, right?
  • Why is it all working? In main, why can I access the parent and each of its children? Is it all because the local variables from family are still intact and haven’t been overwritten by some subsequent function call?

I think I’m misunderstanding where stuff lives in memory in C++. I’d really like to be pointed a resource that explains it well. Thanks in advance.

EDIT

Output from compiling the source and running:

misha@misha-K42Jr:~/Desktop/stackoverflow$ ./a.out 
family:
    parent: 0x2aa47470
    i: 2aa47438
main:
    parent: 0x2aa47470
        child[0]: parent: 0x2aa47470 parent.name 'John Doe'
        child[1]: parent: 0x2aa47470 parent.name 'John Doe'
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T22:15:34+00:00Added an answer on May 19, 2026 at 10:15 pm

    The Child objects that are in the vector survive for the reason that Mark Ransom pointed out, but the pointer to Parent * that each Child contains (which points to p) becomes invalid just as you expected.

    If it appears to work, what likely happend is the compiler’s optimizer inlined family(), and then combined the storage of main(){p} and family(){p} to avoid copying the returned object. This optimization would be likely even without inlining, but nearly certain with it.

    It’s easy to see why it would be allowed in this case, since your Parent class doesn’t customize the copy constructor, but it’s actually allowed regardless. The C++ standard makes special reference to return value optimization, and permits the compiler to pretend that a copy constructor has no side effects, even if it can’t prove this.

    To fix this, the Parent needs to be allocated on the heap, and some other provision would need to be made to free it. Assuming that no time-travel is involved (so that no object can become its own ancestor), this could be easily accomplished by using tr1::shared_ptr (or boost::shared_pointer for pre-TR1 compilers) for the pointer each child holds to its parent.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two classes declared like this: class Object1 { protected ulong guid; protected
I have a class that has a vector of another class objects as a
I have the following class objects: public class VacancyCategory { public int ID {
I have a class that map objects to objects, but unlike dictionary it maps
I have a factory class that populates objects with data. I want to implementing
I have a class that creates several IDisposable objects, all of these objects are
I know that class variables are declared in memory (as opposed to on the
I have a UIImageView based class. At the start of this class, I have
I have some classes with the same super-type. Therefore all of this classes have
I have following code class Test { public: int &ref; int a; Test(int &x)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.