0

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;
Manojkumar Khotele
  • 963
  • 11
  • 25
  • 1
    use rvalue reference && – Anis Belaid Oct 21 '21 at 15:58
  • Are you trying to eliminate the line `auto defaultStructObject = SomeStruct{};` and you just want a pointer? – NathanOliver Oct 21 '21 at 16:00
  • `SomeStruct{};` is a rvalue you need to extend it's life or it will be destroyed at the end of the full expression; if you could take it's address you would get a dangling pointer. You can extend it's life with an rvalue reference or a const reference eg `auto && refToDefaultStructObject = SomeStruct{};` – Richard Critten Oct 21 '21 at 16:03
  • If your class has no arg constructor you can probably do this auto* pointerToMyStructObj = new MyStruct{}; – Angelos Oct 21 '21 at 16:05

2 Answers2

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

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

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;
}
Angelos
  • 169
  • 10