简体   繁体   中英

Function that returns just the constructor

#include <iostream>


struct something{
    int i;

    something(int i) : i(i) {}
};

class otherthing {

    otherthing(){}

    static something foo(int value)
    {
        return { value };
    }
};

In this example what the foo function returns? Am I understand correctly that it creates an object on the heap and returns a pointer? Is this considered bad style? Or is it ok for structs and not classes?

I can feel that it might be a stupid question but I tried to google it and I could not find the answer. I apologize in advance if this is dumb.

In this example what the foo function returns?

Object of type something , initialized with value value .

Am I understand correctly that it creates an object on the heap and returns a pointer?

No. It creates an object with automatic lifetime (typically associated with stack memory). It returns that object and no pointer.

Is this considered bad style?

It's quite useless in this example, but in general this approach is called factory pattern . It allows you to separate creation of object from other logic, and that would be good style actually.

Or is it ok for structs and not classes?

The only difference between struct and class in C++ is the default access modifier. In struct member are by default public , in class members are by default private .

Am I understand correctly that it creates an object on the heap and returns a pointer?

No, it does not return a pointer, it returns an instance of something with automatic storage duration (which is commonly allocated on the stack) which for the return will utilize copy elision

Or is it ok for structs and not classes?

A struct and a class only differ in the default access modifier, besides that there is no difference.

In C++ (unlike C#) classes and structs are identical but for one tiny detail: the default access level for a class is private; for a struct it's public.

In your example, a something object is created on the stack in foo . When foo is called, eg

something s = otherthing.foo();

then the object is copied into s on the stack.

No pointers are involved.

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