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?
Yes, RVO would be allowed in this case - at least if the caller of Something()
was a class member or friend.
I think this is one reason why private inheritance of a non-copyable class is better than doing it 'manually' in each class you want to prevent copying in. In that case there's no accidental loophole.
For example, using boost::noncopyable
:
class NonCopyable : private boost::noncopyable {
public:
NonCopyable() {};
NonCopyable Something();
};
NonCopyable NonCopyable::Something()
{
return NonCopyable(); // causes compile time error, not link time error
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With