编译器报错make_shared()期望左值

Compiler complains make_shared() expects l-value

本文关键字:期望 shared make 编译器      更新时间:2023-10-16

我有一个简单的类。它的一个构造函数接受两个int值作为参数:

simple_class.h

class SimpleClass {
   private:
      int d_ii;
      int d_jj;
   public:
      SimpleClass() : d_ii(40), d_jj(10) {}
      SimpleClass( const int ii, const int jj ) : d_ii(ii), d_jj(jj) {}
};

test.t.cpp

//----------------------------------------------------------------//
//
//  Test Program
#include <memory>
#include <simple_class.h>
int main ( int argc, char * argv[] )
{
   SimpleClass sc1;
   SimpleClass sc2( 10, 20 );
   std::shared_ptr<SimpleClass> spSc1( new SimpleClass(10,12) );
   int ii = 10;
   int jj = 16;
   std::shared_ptr<SimpleClass> spSc2 = std::make_shared<SimpleClass> ( ii, jj );
   std::shared_ptr<SimpleClass> spSc3 = std::make_shared<SimpleClass> ( 10, 16 );
   return 0;
}

在macbook上运行。下面是我的编译语句:

gcc -o test -Itest.t.cpp -lstdc + +

但是它产生了这个错误:

test.t.cpp:18:41: error: no matching function for call to 'make_shared'
 std::shared_ptr<SimpleClass> spSc3 = std::make_shared<SimpleClass> ( 10, 16 );
                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4708:1: note:
      candidate function [with _Tp = SimpleClass, _A0 = int, _A1 = int] not viable: expects an l-value for 1st
      argument
make_shared(_A0& __a0, _A1& __a1)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4692:1: note:
      candidate function template not viable: requires 0 arguments, but 2 were provided
make_shared()
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4700:1: note:
      candidate function template not viable: requires single argument '__a0', but 2 arguments were provided
make_shared(_A0& __a0)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4716:1: note:
      candidate function template not viable: requires 3 arguments, but 2 were provided
make_shared(_A0& __a0, _A1& __a1, _A2& __a2)
^
1 error generated.

所以我的问题是,为什么make_shared()的这种用法不起作用?

std::shared_ptr<SimpleClass> spSc2 = std::make_shared<SimpleClass>( 10, 16 );

请注意,传递左值的版本编译为:

   int ii = 10;
   int jj = 16;
   std::shared_ptr<SimpleClass> spSc2 = std::make_shared<SimpleClass> ( ii, jj );

谁能解释一下这是为什么?

构造函数将参数声明为const(尽管这应该是不必要的)。这里给出的例子将常量传递给make_shared()

您正在用C编译器编译c++代码,请使用g++代替。另外,std::shared_ptr及其相关项是c++ 11的特性,需要在c++编译器上启用。所以你的命令行应该是g++ -o test -I. test.t.cpp -std=c++11(不需要链接libstdc++, g++会自动链接)

编辑:

另外,c++ 4.2不支持c++ 11的特性。在OSX上,使用clang++代替