0
votes

Test.h

#include <memory>
#include <string>
using namespace std;

class A
{
public:
    A GetTitle();
private:
    unique_ptr<A> title;
};

Test.cpp

#include <memory>
#include "Test.h"

A A::GetTitle()
{
    return *this->title.get();
} // Error here

int main()
{
}

I'm getting the following error:

C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

what am i doing wrong here? Is it down to the ownership of this->keyServer? How do i pass just the value back so that i am not at all allowing users of the function to modify the value inside the class without using setter?

1
Updated OP with error comment. I'm not yet calling it.Jimmyt1988
Any reasons for the down vote guys? I even created a brand new project to isolate the error... and provided all code.Jimmyt1988
Why did you pick unique_ptr here? Is it really a resource that only one copy of should exist at a time?Donnie
Well, I thought that i only want my A class to own that title let's say (I know it's made up code)... and i just wanted people to access it but not be able to maniuplate it... so yes i thought unique_ptr was perfect here.Jimmyt1988
Ohhhhh I think this is an issue somewhere else!Jimmyt1988

1 Answers

4
votes

A is not copyable because of the presence of the unique_ptr data member. The GetTitle() member function attempts to make a copy of A, because it returns an A by value, leading to the (misleading) error.

If you want to be able to make copies of A you'll need to provide a copy constructor definition.


On the whole, your example is odd. If A is a unique resource, should you be making copies of it in that member function? And what if A::title actually contains a pointer to a class derived from A? Then the copy operation isn't going to work as intended.