Note that there are some explanatory texts on larger screens.

plurals
  1. POSize of class instance
    primarykey
    data
    text
    <p>I'm working with a class for which the new operator has been made private, so that the only way to get an instance is to write</p> <pre><code>Foo foo = Foo() </code></pre> <p>Writing</p> <pre><code>Foo* foo = new Foo() </code></pre> <p>does not work.</p> <p>But because I really want a pointer to it, I simulate that with the following :</p> <pre><code>Foo* foo = (Foo*)malloc(sizeof(Foo)); *foo = Foo(); </code></pre> <p>so that can test whether the pointer is null to know whether is has already been initialized.</p> <p>It looks like it works, from empirical tests, but is it possible that not enough space had been allocated by malloc ? Or that something else gets funny ?</p> <p><strong>--- edit ---</strong></p> <p>A didn't mention the context because I was not actually sure about why they the new operator was disabled. This class is part of a constraint programming library (gecode), and I thought it may be disabled in order to enforced the documented way of specifying a model.</p> <p>I didn't know about the Concrete Data Type idiom, which looks like a more plausible reason.</p> <p>That allocation scheme may be fine when specifying a standard model --- in which everything is specified as CDTs in the Space-derived class --- but in my case, these instance are each created by specific classes and then passed by reference to the constructor of the class that reprensents the model.</p> <p>About the reason i'm not using the</p> <pre><code>Foo f; Foo *pf = &amp;f; </code></pre> <p>it would be like doing <em>case 1</em> below, which throws a "returning reference to local variable" warning</p> <pre><code>int&amp; f() { int a=5; return a; } // case 1 int&amp; f() { int a=5; int* ap=&amp;a; return *ap; } int&amp; f() { int* ap=(int*)malloc(sizeof(int)); *ap=5; return *ap; } </code></pre> <p>this warning disappears when adding a pointer in <em>case 2</em>, but I guess it is because the compiler loses tracks.</p> <p>So the only option left is <em>case 3</em> (not mentioning that additionaly, <code>ap</code> is a member of a class that will be initialized only once when f is called, will be null otherwise, and is the only function returning a reference to it. That way, I am sure that <code>ap</code> in this case when lose its meaning because of the compilier optimizing it away (may that happen ?)</p> <p>But I guess this reaches far too much beyond the scope of the original question now...</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.
    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