3

I have class without copy constructor or assignment operator. I need to create and initialize a instance of that class. How do I do that?

Code with the problem (example):

class Q
{
    int w;
    public:
    Q():w(19){};
    Q(const Q&) = delete;
    Q& operator = (const Q&) = delete;

    static Q sQ;
};

Q Q::sQ = Q();

On ideone

Use case: I have a class that is derived from QObject and so has its assignment operator and copy constructor deleted. There should be a static instance of the class available, how can that be achieved?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Srv19
  • 3,458
  • 6
  • 44
  • 75
  • 1
    Doesn't simple `Q Q::sQ;` work for you? – HolyBlackCat May 25 '16 at 19:17
  • 3
    There is a proposal to make copy elision guaranteed, so code like this would compile even with deleted copy and move constructors. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html – Brian Bi May 25 '16 at 19:21
  • It's like all of your Q's are pregnant at the same time with the same baby Q; curious, pregnant itself in an infinite cycle. Well, adopting the definition Q Q::sQ; proposed by HolyBlackCat, with a member function void f() { std::cout << "smoke and mirrors\n"; } You can do now Q q; q.sQ.sQ.sQ.sQ.sQ.sQ.sQ.sQ.sQ.sQ.sQ.sQ.sQ.f(); – Loreto May 25 '16 at 19:56
  • 1
    @Loreto that's some image... – Srv19 May 25 '16 at 20:11
  • 1
    @Srv19 You have got a paradox machine. – Loreto May 25 '16 at 20:19

1 Answers1

5

You can use the uniform initialization syntax and construct the class with a empty set of curly braces

Q Q::sQ{};

or you can even drops the curly braces like:

Q Q::sQ;

Both will default construct sQ.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • std::mutex is a good example, where both copy constructor and assignment operator are =delete; If your class Yourcalss { static mutex mtx; }; you can initialize a static mutex Yourcalss::mtx{} – Kemin Zhou Jul 23 '18 at 04:17