Search code examples
c++copy-constructorrvo

Is RVO allowed when a copy constructor is private and not implemented?


Suppose I have a class where the copy constructor is private and not implemented (to make the object non-copyable)

class NonCopyable {
// whatever
 private:
    NonCopyable( const NonCopyable&);
    void operator=(const NonCopyable&);
 };

Now in some member function of the same class I write code that returns an object of that class:

NonCopyable NonCopyable::Something()
{
    return NonCopyable();
}

which is a case when RVO could kick in.

RVO still requires that a copy constructor is accessible. Since the possible call to the copy constructor is done from within the same class member function the copy constructor is accessible. So technically RVO is possible despite the fact that the intent was to prohibit using the copy constructor.

Is RVO allowed in such cases?


Solution

  • Your example is quite interesting.

    This is the typical C++03 declaration.

    class NC {
    public:
        NC NC::Something() {
            return NC();
        }
    
    private:
        NC(NC const&);
        NC& operator=(NC const&);
    };
    

    Here, as noted, RVO may kick in even though we semantically wanted to avoid copying.

    In C++03, the solution is to delegate:

    class NC: boost::noncopyable {
    public:
        NC NC::Something() { // Error: no copy constructor
            return NC();
        }
    };
    

    In C++11, we have the alternative of using the delete keyword:

    class NC {
    public:
        NC NC::Something() { // Error: deleted copy constructor
            return NC();
        }
    
    private:
        NC(NC const&) = delete;
        NC& operator=(NC const&) = delete;
    };
    

    But sometimes, we want to prevent copy, but would like to allow Builder (as in the Pattern).

    In this case, your example works as long as RVO kicks in, which is a bit annoying as it is, in essence, non-standard. A definition of the copy constructor should be provided but you wish it not to be used.

    In C++11, this usecase is supported by deleting copy operations and defining move operations (even privately).