为什么这段代码不能编译?

Che*_*Alf 0 c++ constructor const move-semantics

有了const,如评论所示,msvc 11和g ++ 4.7.0拒绝编译:

#include <memory>       // std::unique_ptr
#include <utility>      // std::move
using namespace std;

struct CommandLineArgs
{
    typedef unique_ptr<
        wchar_t const* const [],
        void(*)( wchar_t const* const* )
        > PointerArray;

    //PointerArray const  args;         // Oops
    PointerArray        args;
    int const           count;

    static wchar_t const* const* parsed(
        wchar_t const       commandLine[],
        int&                count
        )
    {
        return 0;
    }

    static void deallocate( wchar_t const* const* const p )
    {
    }

    CommandLineArgs(
        wchar_t const   commandLine[]   = L"",
        int             _               = 0
        )
        : args( parsed( commandLine, _ ), &deallocate )
        , count( _ )
    {}

    CommandLineArgs( CommandLineArgs&& other )
        : args( move( other.args ) )
        , count( move( other.count ) )
    {}
};

int main()
{}
Run Code Online (Sandbox Code Playgroud)

错误消息似乎没有特别的信息,但这里是g ++的输出:

main.cpp: In constructor 'CommandLineArgs::CommandLineArgs(CommandLineArgs&&)':
main.cpp:38:38: error: use of deleted function 'std::unique_ptr::unique_ptr(const std::unique_ptr&) [w
ith _Tp = const wchar_t* const; _Dp = void (*)(const wchar_t* const*); std::unique_ptr = std::unique_ptr]'
In file included from c:\program files (x86)\mingw\bin\../lib/gcc/mingw32/4.7.0/include/c++/memory:86:0,
                 from main.cpp:1:
c:\program files (x86)\mingw\bin\../lib/gcc/mingw32/4.7.0/include/c++/bits/unique_ptr.h:402:7: error: declared here

为什么?

BЈо*_*вић 6

你不能移动const对象.错误是因为您的移动构造函数.

unique_ptr,删除了复制构造函数和移动构造函数,声明为:

unique_ptr( const unique_ptr & other );
unique_ptr( unique_ptr && other );
Run Code Online (Sandbox Code Playgroud)

由于你的unique_ptr是dec的const,它选择复制构造函数,而不是移动构造函数.

  • 是的,我认为实际上const成员的常数胜过了移动后的状态的未指定性. (3认同)