Note that there are some explanatory texts on larger screens.

plurals
  1. POinvalid initialization of non-const reference of type in gcc but not Visual Studio
    primarykey
    data
    text
    <p>I have some code where IInterface is an abstract class.</p> <p>I was writing this </p> <pre><code>IInterface &amp;q = InterfaceImpl(); </code></pre> <p>and compiled it in Visual Studio 2008 and it worked fine. Then I ported it to a gcc project and suddenly I got this error:</p> <pre><code>error: invalid initialization of non-const reference of type 'IInterface&amp;' from a temporary of type 'InterfaceImpl' </code></pre> <p>When trying to find out what is wrong I found this thread <a href="https://stackoverflow.com/questions/8293426/error-invalid-initialization-of-non-const-reference-of-type-int-from-an-rval">error: invalid initialization of non-const reference of type ‘int&amp;’ from an rvalue of type ‘int’</a> and at least understand now what is wrong. So changing it to this:</p> <pre><code>InterfaceImpl i = InterfaceImpl(); IInterface &amp;q = i; </code></pre> <p>made it compile:</p> <p>However, The lifetime of these two objects are the same, so I don't really understand why gcc can not create a temporary object as apparently MS did. I assume that this is defined by the standard? When I look at the link above, I can understand why it makes no sense with something like a base type, but why does it need to get an error in case of an object?</p> <p>I also tried it like this, but then I get the error that IInterface is an abstract class and can not be instantiated.</p> <pre><code>IInterface i = InterfaceImpl(); </code></pre> <p><code>i</code> should be initialized, not instantiated. Does this mean I would need a copy constructor or assignment operator in InterfaceImpl to make this work or why do I get this error? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload