KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've tried to Google this issue, and I can't find anything that I see as relevant. So I must be looking for the wrong thing; none the less, I'd appreciate some advice... Foobar &foobar = *new Foobar(someArg, anotherArg); Is it just me or does that seem smelly? I understand that the new keyword is designed for use with pointers (as such): Foobar *foobar = new Foobar(someArg, anotherArg); But what if you don't require a pointer on that instance, and you would like to use a reference instead? Or, is it the case that you don't need to explicitly initialize it (much like local variables); and if this is the case, what if I want to initialize with parameters? The following does not work (unless I'm doing something wrong): // the last argument is of type: int Foobar &foobar(someArg, anotherArg); ... gives the compiler error: initializer expression list treated as compound expression invalid initialization of non-const reference of type ‘Foobar&’ from a temporary of type ‘int’ And also this doesn't seem to work: Foobar &foobar = Foobar(someArg, anotherArg); ... gives the compiler error: error: invalid initialization of non-const reference of type ‘Foobar&’ from a temporary of type ‘Foobar’ Update 1: Bare in mind that I am returning this value, so I don't want to use a local variable; I want to use a value on the heap, not the stack: Foobar &helloWorld() { Foobar &foobar = *new Foobar(someArg, anotherArg); foobar.HelloWorld(); return foobar; } Should I just be using pointers instead, or is this completely valid?
Tags (comma-separated)
Save Edits
Cancel