Home > Blockchain >  How can I have a pointer to default struct object in a single statement?
How can I have a pointer to default struct object in a single statement?

Time:10-22

I can first get a default struct object and then a pointer to it. But I suspect there must be some graceful way to do it; probably in a single statement.

auto defaultStructObject = SomeStruct{};
auto pointerToDefaultStructObject = &defaultStructObject;

CodePudding user response:

But I suspect there must be some graceful way to do it; probably in a single statement.

If you insist on having in one line, one quick way is immediately invoking lambda function, which creates a static SomeStruct and there by extended lifetime and can be addressable:

struct SomeStruct { std::string name{};  };

int main()
{ 
    SomeStruct* ptrStruct = []{ static SomeStruct obj{"default"}; return &obj; }();
    std::cout << ptrStruct->name;  // prints "default"
} 

See a Demo

CodePudding user response:

You can probably use the first line inside the main function.

class MyClass {
    
    public:
    
    MyClass() {};
    void Print() const {std::cout << "hello world \n";}
};

int main() {
   
    auto* pObj = new MyClass();
    pObj->Print();
    return 0;
}

CodePudding user response:

auto defaultStructObject = SomeStruct{}, *pointerToDefaultStructObject = &defaultStructObject;

Online Demo

  • Related