manabreak
manabreak

Reputation: 5597

Is there a way to enforce a reference lvalue?

I was wondering if there's a way to enforce the usage of a reference lvalue? Suppose a following scenario:

class Foo
{
public:
    Foo()
    {
        std::cout << "Foo ctor()" << std::endl;
    }

    ~Foo()
    {
        std::cout << "Foo dtor()" << std::endl;
    }
};

class FooFactory
{
public:
    Foo& create()
    {
        m_foo = new Foo();
        return *m_foo;
    }
    void destroy()
    {
        delete m_foo;
    }
private:
    Foo* m_foo;
};

int main()
{
    FooFactory factory;

    Foo& foo = factory.create();
    factory.destroy();

    return 0;
}

This code will print out the following:

Foo ctor()
Foo dtor()

Now, if I change the main() function like this:

int main()
{
    FooFactory factory;

    Foo foo = factory.create();
    factory.destroy();

    return 0;
}

The program outputs:

Foo ctor()
Foo dtor()
Foo dtor()

AFAIK, this is because there's a copy created in main() of the foo object and it is destroyed when main() goes out of scope. So, the question is: is it possible to enforce the use of Foo foo& instead of Foo foo so that there would be no copies made?

Upvotes: 1

Views: 72

Answers (1)

Praetorian
Praetorian

Reputation: 109119

If you have a C++11 compiler, then explicitly delete the copy constructor (and optionally the copy assignment operator) for Foo

Foo(Foo const&) = delete;
Foo& operator=(Foo const&) = delete;

For a pre-C++11 compiler, declare the two private and leave them undefined

private:
  Foo(Foo const&);
  Foo& operator=(Foo const&);

Upvotes: 4

Related Questions