Question

I'm actually working on pointers to user-defined objects but for simplicity, I'll demonstrate the situation with integers.

int* f(){
    return new int(5);
}

void f2(int* i){
    *i = 10;
}

int main(){

    int* a;
    int* b = new int();

    a = f();
    f2(b);

    std::cout << *a << std::endl;    // 5
    std::cout << *b << std::endl;    // 10

    delete b;
    delete a;
    return 0;
}

Consider that in functions f() and f2() there are some more complex calculations that determine the value of the pointer to be returned(f()) or updated through paramteres(f2()).

Since both of them work, I wonder if there is a reason to choose one over the other?

Était-ce utile?

La solution

From looking at the toy code, my first thought is just to put the f/f2 code into the actual object's constructor and do away with the free functions entirely. But assuming that isn't an option, it's mostly a matter of style/preference. Here are a few considerations:

The first is easier to read (in my opinion) because it's obvious that the pointer is an output value. When you pass a (nonconst) pointer as a parameter, it's hard to tell at a glance whether it's input, output or both.

Another reason to prefer the first is if you subscribe to the school of thought that says objects should be made immutable whenever possible in order to simplify reasoning about the code and to preclude thread safety problems. If you're attempting that, then the only real choice is for f() to create the object, configure it, and return const Foo* (again, assuming you can't just move the code to the constructor).

A reason to prefer the second is that it allows you to configure objects that were created elsewhere, and the objects can be either dynamic or automatic. Though this can actually be a point against this approach depending on context--sometimes it's best to know that objects of a certain type will always be created and initialized in one spot.

Autres conseils

If the allocation function f() does the same thing as new, then just call new. You can do whatever initialisation in the object's construction.

As a general rule, try to avoid passing around raw pointers, if possible. However that may not be possible if the object must outlive the function that creates it.

For a simple case, like you have shown, you might do something like this.

void DoStuff(MyObj &obj)
{
    // whatever
}

int Func()
{
    MyObj o(someVal);
    DoStuff(o);
    // etc
}

f2 is better only because the ownership of the int is crystal clear, and because you can allocate it however you want. That's reason enough to pick it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top