Reader Q&A: How can I prevent a type from being instantiated on the stack?

Anubhav asked:


An interesting question has come up in our project while debating operator new as a class member function. Specifically, the question is about whether such a class should be allowed to be instantiated on stack. The understanding is that a class providing its own operator new would likely have special layout considerations which would not be met if the object of such a class is instantiated locally.



The class specific operator new is used when allocating on the heap, but objects can still be allocated on the stack. The only way I know to prevent an object from being instantiated on the stack is by forcing creation through a factory function that always allocates on the heap, for example:



#include

class X {
// make all ctors private
X();
X(const X&);
// and any other ctors go here

public:
// Factory function (or it could be a nonmember friend)
static auto make( /*…*/ ) { return std::unique_ptr(new X( /*…*/ )); }

// the usual public member functions go here
};

int main()
{
X x; // error
auto x2 = X::make(); // ok
}


Filed under: C++
 •  0 comments  •  flag
Share on Twitter
Published on May 03, 2014 20:35
No comments have been added yet.


Herb Sutter's Blog

Herb Sutter
Herb Sutter isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Herb Sutter's blog with rss.