3

Consider the following code:

class Outer
{   
class Inner
{
public:
    Inner(Inner&& i):outers(std::move(i.outers)),test(std::move(test))
    {}

    void addOuter(const Outer& o) {outers.push_back(std::move(o));} 
private:
    std::vector<Outer> outers;      
    std::unique_ptr<std::string> test;      
};

public:
Outer(Outer&& o):inners(std::move(o.inners))
{}
private:
std::vector<Inner> inners;

};

When I try to compile the code above on Visual Studio 2012, I get the following error:

Error 1 error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

Apparently the compiler invokes the copy constructor instead of the move constructor in the push_back found in the addOuter method. Is this a compiler bug? If not why, for this specific case, isn't the move constructor called?

5
  • 3
    Possibly because o is passed as a const reference to addOuter. Commented Dec 16, 2013 at 19:55
  • 1
    @Andrey That should be an answer. Commented Dec 16, 2013 at 20:05
  • It looks like you need an void addOuter(Outer&& o) {outers.push_back(std::move(o));} overload Commented Dec 16, 2013 at 20:05
  • BTW, that is some terribly formatted code...
    – dtech
    Commented Dec 16, 2013 at 20:14
  • 2
    Your move constructor should initialise test from i.test, not from itself. Commented Dec 16, 2013 at 20:50

1 Answer 1

13

Because o is passed as a const reference to addOuter.

2
  • 2
    @register no, this is right. The const reference makes std::move yield an lvalue reference. Removing the const would result in the move yielding a nameless rvalue. Commented Dec 16, 2013 at 20:37
  • I cannot upvote until the answer is edited again. Please do so and I will remove my downvote.
    – register
    Commented Dec 17, 2013 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.