Will heap allocated objects have their members allocated on the stack?

后端 未结 4 472
醉梦人生
醉梦人生 2021-01-22 17:15

Let\'s consider this example.

class StaticlyManagedObject
{
   //some class members....
}
class DynamiclyManagedObject
{
   StaticlyManagedObject _staticlyManage         


        
4条回答
  •  长发绾君心
    2021-01-22 17:59

    Whether a member of your class is another class, or an elementary data type:

    class DynamiclyManagedObject
    {
       StaticlyManagedObject _staticlyManagedObject;
       int some_integer;
    };
    

    It doesn't matter whether the class member is another class, or an elementary data type, such as an int. Both "_staticlyManagedObject" and "some_integer" are completely identical to each other, except for their type (of course, that's not exactly a trivial attribute). One is an int, the other one is some other class. The type of a class member does not affect its scope. Either the entire class is dynamically allocated, or it's not. Or it's allocated in the automatic scope (on the stack, as you say).

    The only exception to the rule is a static class member:

    class DynamiclyManagedObject
    {
       StaticlyManagedObject _staticlyManagedObject;
       int some_integer;
    
       static std::string some_string;
    };
    

    The rules are different for some_string. Note that this is a real static class member, and not a class member whose type happens to be StaticallyManagedObject.

提交回复
热议问题