开发者

Problem with "moveable-only types" in VC++ 2010

I recently installed Visual Studio 2010 Professional RC to try it out and test the few C++0x features that are implemented in VC++ 2010.

I instantiated a std::vector of std::unique_ptr, without any problems. However, when I try to populate it by passing temporaries to push_back, the compiler complains that the copy constructor of unique_ptr is private. I tried inserting an lvalue by moving it, and it works just fine.

#include <utility>
#include <vector>

int main()
{
    typedef std::unique_ptr<int> int_ptr;

    int_ptr pi(new int(1));

    std::vector<int_ptr> vec;

    vec.push_back(std::move(pi));      // OK
    vec.push_back(int_ptr(new int(2))); // compiler error
}

As it turns out, the problem is neither unique_ptr nor vector::push_back but the way VC++ resolves overloads when dealing with rvalues, as demonstrated by the following code:

struct MoveOnly
{
    MoveOnly() {}
    MoveOnly(MoveOnly && other) {}

private:

    MoveOnly(const MoveOnly & ot开发者_Go百科her);
};

void acceptRValue(MoveOnly && mo) {}

int main()
{
    acceptRValue(MoveOnly()); // Compiler error
}

The compiler complains that the copy constructor is not accessible. If I make it public, the program compiles (even though the copy constructor is not defined).

Did I misunderstand something about rvalue references, or is it a (possibly known) bug in VC++ 2010 implementation of this feature?


Unfortunately, /Za is buggy. It performs an elided-copy-constructor-accessibility check when it shouldn't (binding rvalue references doesn't invoke copy constructors, even theoretically). As a result, /Za should not be used.

Stephan T. Lavavej, Visual C++ Libraries Developer (stl@microsoft.com)


First of all, you need a close ):

vec.push_back(int_ptr(new int(2))); // compiler error

Now I have no compiler error neither the first nor the second case.

I use Visual Studio 2010 Beta.


I noticed that I had disabled language extensions (\Za). With the extensions enabled, the code gets correctly compiled. I still think this is a bug since the code presented here is perfectly standard (as far as I know) and does not rely on any Microsoft extensions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜