0

Long time reader first time poster. Searching for this is very obscure so I couldn't find anything.

Anywho, if I declare a struct inside of a class. Then I have a class method that creates instances of said struct, what is the lifespan of the created struct instance?

For instance in my header:

class test_class
{
     Public:
          void test_function(int, string);

     private:
          struct test_struct
          {
               int foo;
               string bar;
          };

          test_struct * storage;
}

Then in test_class.cpp

void test_function(int num, string name)
{
     test_struct t1;
     t1.foo = num;
     t1.bar = name;

     storage = new test_struct [<some_size>];
     storage[<some_element>] = t1;
}

So, I make an instance of my test_class and call the test_function. t1 is created and then stored successfully in the hypothetical array, but does it stay saved in the array? Or does it get deleted when the function exits because the scope shifts? Does t1 become a member variable of the class? Would I need t1 to be a pointer to a test_struct and have an array of test_struct pointers?

Thank you in advance for the help.

darkcammo
  • 3
  • 2
  • Instead of using pointers, use `std::vector storage;`. Then everything takes care of itself. – PaulMcKenzie Dec 05 '14 at 04:32
  • Unfortunately, I have to do it in this manner. This isn't the assignment itself, but it is a reduction of the idea. I'm representing a priority queue with a heap represented by an array @.@ – darkcammo Dec 05 '14 at 04:35
  • A `vector` does exactly what your psuedo-code is attempting to do, only correctly. A vector calls `new` and `delete`, no different than what you would attempt to do (but again, only safer). – PaulMcKenzie Dec 05 '14 at 04:37
  • Understood. Unfortunately, I have to use an array. – darkcammo Dec 05 '14 at 04:37
  • 1
    Your code uses a pointer, not an array. Read my comment again -- a vector does *exactly* what you're doing in a controlled, safe manner. The array is there, you just have to get to it. At this point, your code has a memory leak since you didn't issue a call to `delete`. – PaulMcKenzie Dec 05 '14 at 04:40
  • I'm afraid we're not on the same page. My code does use an array. I point storage at a newly created dynamic array `storage = new test_struct [];` There is no memory leak, the array is later deleted in code not shown. None of this answers my actual question. I'm trying to understand how and if the struct instance t1 is getting stored into storage. – darkcammo Dec 05 '14 at 04:45
  • Well, since the last line `storage[x] = t1;` is an assignment, you will have issues if `test_struct` doesn't have a user-defined copy constructor and assignment operator. You may have two test_structs with `storage` pointing to the same memory. – PaulMcKenzie Dec 05 '14 at 04:50
  • test_function is a function, not a method of the class test_class, hence it cannot access anything `private` inside test_class, whether it's a nested structure or a method or a data member. If you declared test_function as a friend, then you could access it. – franji1 Dec 05 '14 at 04:54

2 Answers2

1

Lifetime has nothing to do with nesting of class definition.

This statement

 test_struct t1;

declares a local variable whose lifetime ends at the closing right brace of the block containing the declaration. It declares a local variable because it's in a block in a function definition.

This statement

 storage = new test_struct [<some_size>];

dynamically creates <some_size> instances of test_struct. The lifetime of that array ends when you delete[] it. If you do.

This statement

storage[<some_element>] = t1;

is a copy assignment, copying the value of t1. It doesn't create a new instance.


Check out the SO C++ booklist to find a C++ textbook that suits you. If you can, get someone with higher reputation to help you, so that you can read the deleted answers. For unfortunately, the existing community effort was at one time deleted and replaced with a summary.

Community
  • 1
  • 1
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Thank you for getting back to me. So the struct instance t1 is being copied into the specified element of the storage array? Then when the function exits, the original t1's lifetime ends, but a copy is saved in storage until storage is `delete [] storage;`? – darkcammo Dec 05 '14 at 04:54
-1

Looking at your question, looks like you are confused about the struct type inside the class. If it helps, here's a bit of explanation with

      struct test_struct
      {
           int foo;
           string bar;
      };

inside the class, you've just created a new type that's encapsulated inside the class. (Treat it like any other type). Answers to your questions 1.t1 is created and then stored successfully in the hypothetical array, but does it stay saved in the array? Or does it get deleted when the function exits because the scope shifts?

Answer: Yes it copies into the array, as mentioned in the previous answer. Its a copy assignment (bit-wise copy semantics), so, your array's element now has the value copied to it from t1

  1. Does t1 become a member variable of the class? Would I need t1 to be a pointer to a test_struct and have an array of test_struct pointers?

Answer: t1 is a local variable (allocated on the stack), its not a member variable of the class. With storage allocated on heap (new) you have an array of elements of test_struct, and then you simply copy the local t1's value to your array. Essentially, you are copying the value of t1 to array before t1 is destroyed when it goes out of scope. You don't need to create a array to pointer to test_struct, (ofcourse if there are some compulsive reasons, in such a case you allocate memory to test_struct as well).

your "storage" member is allocated on heap, so, make sure that you call delete[] to reclaim the memory.

Hope it helps!

sanjayk79
  • 542
  • 3
  • 15
  • **-1** "Its a copy assignment (bit-wise copy semantics)", no it's not bit-wise copying. Not even as a special case for this particular example. This example includes a `string` member, whose copy constructor is invoked to do the copying. – Cheers and hth. - Alf Dec 05 '14 at 07:39
  • What is this statement? storage[] = t1; Is it not assignment operation? When the assignment happens the member will copied bit-wise fashion. However, std::string has its own assignment implementation that does the deep copy. Not sure why you downvoted, before understanding the statement int its entirety. – sanjayk79 Dec 05 '14 at 07:43
  • copying via assignment or construction is not bitwise copying. if it were then copied pointers would be pointing at the entirely wrong things, and so on. copying via `memcpy` is (as an example) bitwise copying. re "the member will copied bit-wise fashion", no, not at all. – Cheers and hth. - Alf Dec 05 '14 at 07:52
  • FYI http://en.wikipedia.org/wiki/Copy_constructor#Bitwise_Copy_Constructor this is what I meant by bitwise copy "semantic". Also, you are wrong in your response "string member, whose copy constructor is invoked to do the copying". No, when storage[] = t1; is called, string class's assignment operator would be called, and not its copy-constructor. – sanjayk79 Dec 05 '14 at 07:58
  • yes, where I wrote "copy constructor" should be "copy assignment operator". sorry for the typo. anyway, bitwise copying does not mean copy constructor or copy assignment operator. there is no such thing as a "Bitwise copy constructor" in C++; the Wikipedia article is rather low quality & misleading. thanks for making people aware of that. – Cheers and hth. - Alf Dec 05 '14 at 08:06
  • you are not getting the word "Semantic" which means. simple variable-by-variable assignment copy of all the components of an object. Your down-voting is not justified with a preconceived notion of what you think is a bit-wise copy semantic vs what it actually is. I demand that you restore the downvote you made! – sanjayk79 Dec 05 '14 at 08:09
  • see e.g. http://stackoverflow.com/a/17185038/464581 for another SO denizen saying the same as me. but don't take our word for it. get yourself a copy of the C++ standard (or a free draft). – Cheers and hth. - Alf Dec 05 '14 at 08:18
  • Refer "Inside the C++ Object Model" By Stanley B. Lippman Page 52, with reference to C++ Annotated Reference Manual (ARM) where it clearly describes "Bitwise Copy Semantics". Nonetheless, I would like stop this here. – sanjayk79 Dec 05 '14 at 08:23
  • yes there is such a thing as bitwise copy semantics. for example, as i noted in first comment, you have that via e.g. `memcpy`. i think, wrt. the silly arguing, that you are simply not getting the fact that you are the person who has the potential for learning technical stuff here, while i (or possibly both of us) have the potential to learn yet a bit more about the human condition etc. – Cheers and hth. - Alf Dec 05 '14 at 08:58