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"
}
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;