mercredi 22 février 2017

Returning non-copyable non-movable object with explicit constructor

If we have a non-movable, non-copyable class with non-explicit constructor, we can return it and use as follows (in C++11):

#include <iostream>
class NonCop
{
public:
    /*non explicit*/ NonCop(int a, int b) : number(a + b) {}
    NonCop(const NonCop&) = delete;
    int number;
};

NonCop get_non_cop()
{
    return {1, 2};
}

int main()
{
    NonCop &&nc = get_non_cop();
    std::cout << "three: " << nc.number << std::endl;
    return 0;
}

However if the constructor is explicit, it doesn't work. Is there any method of doing this in C++11/C++14 with no modifications in NonCop?

Currently I'm using workaround with deriving from NonCop with wrapper that "deexplicits" the constructor but it doesn't seem very pretty.

Aucun commentaire:

Enregistrer un commentaire