开发者

How best to pass a reference to a function?

Given the following code:

[example.h]

class MyClass
{
public:
    MyClass();
    std::string name;
    std::string address;
    bool method (MyClass &object);
};

[example.cpp]

MyClass::MyClass()
{
}
bool MyClass::method (MyClass &object) {
  try {
      object.name = "New Name";
      std::cout << "Name: " << object.name << " " << object.address << std::endl;
      return true;
  }
  catch (...) {
      return false;
  }
}

[test.cpp]

#include "example.h"

int main()
{
    MyClass myC;

    myC.address = "address";
    bool quest = myC.method(myC);
}

What is the difference between the 开发者_Go百科way I've called myC.method in main above, and this alternative way of doing so:

MyClass *myC = new MyClass(); 
bool quest = myC.method(*myC); 

Which is better and why?


In both cases you can send the same value but simply stick with current code is better since it's without pointer dereference and new. You need to take care of delete'ing the object once you are finished with it, which I don't think you need here.

And it's better to use MyClass &object const in the method function so that the reference passed in doesn't get changed.


Using new (and dynamic memory allocation in general) is better if you need the object to last longer that the scope of the function it's being called in. If it's just for a known duration the MyClass myC; local scope version is best (because it's simpler to read and maintain).

When using new your object "myC" won't be deleted until you call delete.

However if you just define it as a local object it will get deleted when it goes out of scope:

{
 MyClass myC;
 myC.DoSomeStuff();
} // It'll be destroyed here
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜