简体   繁体   中英

c++: When to pass pointers versus returning objects

I've just begun using c++ and I was wondering if there was some guideline around when to do the following:

Let's say I want to return a struct or object. Which of these approaches would be better under what circumstances?

void PopulateStruct(MyStruct* struct) {
      struct->a = x;
      struct->b = y;
}

void Caller() {
    MyStruct s;
    PopulateStruct(&s);
}

OR:

MyStruct PopulateStruct() {
    MyStruct s;
    s.a = x;
    s.b = y;
    return s;
}

void Caller() {
    MyStruct s = PopulateStruct();
}

My basic understanding is that if the struct / object is pretty small then the latter option is probably fine (better?) since the copy will be fast and compilers might also use RVO to avoid an actual copy.

And perhaps if the object is really large then you want the former to avoid that copy?

According to the CppCoreGuidelines by Herb Sutter and Bjarne Stroustrup, the second example is the recommended way. It makes reasoning on the code easier and does not force you to create uninitialized objects in some situations.

See guideline F.20 .

A return value is self-documenting, whereas a & could be either in-out or out-only and is liable to be misused.

In modern compilers, returning an object can be done with move semantics, and even without move semantics it would be fast enough.

It depends on whether you want scope destruction to be applied or you want the programmer to take care of the ownership of the object you are returning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM