Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return local value from function without triggering copy constructor

I am attempting to delete the copy constructor using the c++ type system to prevent copying an object.

struct DeleteCopyConstructor {
    DeleteCopyConstructor() {};
    DeleteCopyConstructor(DeleteCopyConstructor& op2) = delete;
    DeleteCopyConstructor(const DeleteCopyConstructor& op2) = delete;
};

DeleteCopyConstructor f() {
    DeleteCopyConstructor d;
    // initialize d...
    return d;
}

The error is:

error: use of deleted function ‘DeleteCopyConstructor::DeleteCopyConstructor(const DeleteCopyConstructor&)’

I've read about copy elision, but it appears to be a compiler optimization, so I don't think it applies. How can I return d without triggering copy construction?

like image 727
jcarpenter2 Avatar asked Jun 25 '17 20:06

jcarpenter2


People also ask

Why is the copy constructor called when returning an object?

That's what your reference is talking about. No values are replaced, the copy constructor is called in order to intialize one object as a duplicate of another, separate object of the same type. However, it is not so simple as the copy constructor always being called when an object is returned.

Can We pass arguments by value in a copy constructor?

A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.

What happens when you return a local object from a function?

Whenever you return a local object of a function, the compiler tends to keep and redirect the local object to the place you return (so the local object won't be deleted and compiler need not to create another object to copy the detail of the local object.) After the statement finishes (;),the local object is then deleted.

How to return a local variable created inside a function?

The following article discusses the way to return a local variable created inside a function, which can be done by returning a pointer to the variable from the called function to the caller function. What happens when you try to return a local variable as usual?


1 Answers

In C++17 the compiler is guaranteed to elide the copy. However in all cases you still need to have a valid copy constructor.

So if you're just concerned about performance then you don't have to do anything. If you want to delete the copy constructor because the value logically shouldn't be copyable then there is no way to do it as far as I know. You'd have to return a std::unique_ptr<T> or take the value by reference and move into it that way. Edit: Or define a move constructor.

like image 184
Timmmm Avatar answered Nov 13 '22 10:11

Timmmm