C++ 通过';自动';声明的标准::共享\u ptr<;派生>;至标准::共享\u ptr<;基地>&;
使用C++ 通过';自动';声明的标准::共享\u ptr<;派生>;至标准::共享\u ptr<;基地>&;,c++,c++11,C++,C++11,使用g++-std=c++11编译-迂腐错误-Wall-Wextra-g void foo(std::shared_ptr<Base>& ptr) { std::cout << "foo()\n"; std::cout << "count = " << ptr.use_count() << "\n"; } int main(int argc,
g++-std=c++11编译-迂腐错误-Wall-Wextra-g
void foo(std::shared_ptr<Base>& ptr) {
std::cout << "foo()\n";
std::cout << "count = " << ptr.use_count() << "\n";
}
int main(int argc, char* argv[]) {
auto d = std::make_shared<Derived>(5);
foo(d);
return 0;
}
void foo(std::shared_ptr&ptr){
标准::cout
所有带有auto
的类型声明是否都生成r值
不,这与这里无关
d
是一个std::shared\u ptr
,但是foo
接受std::shared\u ptr
,然后需要将其转换为std::shared\u ptr
,这是一个临时对象(右值)并且不能绑定到对非常量的左值引用,即std::shared_ptr&
这与左值或右值无关。使用普通指针,而不是std::shared_ptr
,将导致相同的错误(尽管std::shared_ptr
也会为这种情况添加额外的成分)C++根本不这样工作。
shared_ptr.cpp:47:10: error: cannot bind non-const lvalue reference of type ‘std::shared_ptr<Base>&’ to an rvalue of type ‘std::shared_ptr<Base>’
foo(d);