c++ pointer scope

前端 未结 4 574
终归单人心
终归单人心 2020-12-25 13:47

What happens when you have the following code:

void makeItHappen()
{
    char* text = \"Hello, world\";
}

Does text go out of

4条回答
  •  悲&欢浪女
    2020-12-25 13:55

    The variable text does go out of scope (however the string literal is not deleted).

    For objects that you allocate with new (like your SomeClass), you need to explicitly delete them. If you want objects allocated like this to be automatically deleted, take a look at boost smart pointers (std::unique_ptr if your compiler is c++0x aware).

    This will automatically delete the allocated object when the shared pointer goes out of scope.

    Your code would then look like this:

    int main(int argv, char **argv)
    {
      boost::scoped_ptr ptr(new SomeClass);
      // the object is automatically deleted
      return 0;
    }
    

    Note: In this particular example, you could also use std::auto_ptr (but this will be deprecated in c++0x).

    Note 2: As was pointed out in the comments by Kos, it is in this case more appropriate to use boost::scoped_ptr or std::unique_ptr (c++0x). My answer first used boost::shared_ptr, which is more appropriate if you need to share ownership of a pointer between several classes for instance.

提交回复
热议问题