C++11 c++;:STL中的智能指针
这是我的代码:C++11 c++;:STL中的智能指针,c++11,shared-ptr,C++11,Shared Ptr,这是我的代码: class Test { public: Test(){ cout << "constructor" << endl; } ~Test(){ cout << "destructor" << endl; } void show(){ cout << "show" << endl; } }; int main() { vector<shared_ptr<Test>
class Test
{
public:
Test(){ cout << "constructor" << endl; }
~Test(){ cout << "destructor" << endl; }
void show(){ cout << "show" << endl; }
};
int main()
{
vector<shared_ptr<Test>> vec;
vec.push_back(make_shared<Test>(Test()));
vec[0]->show();
vec.clear();
return 0;
}
在我看来,show
之前的constructor
和destructor
来自Test()
。我们创建了一个临时对象作为make_shared()
的参数。因此,我们在这里调用构造函数和析构函数。但是我不知道为什么在
show
之后没有任何constructor
。是否将_共享成为新对象?在show
之后,如果没有任何构造函数,我们怎么可能有析构函数呢?或者是因为编译器做了一些我不知道的事情 这里必须注意编译器生成的副本构造函数(或根据编译器实现省略的副本):
类测试
{
公众:
Test(){cout必须注意此处编译器生成的副本构造函数(或省略的副本,具体取决于编译器实现):
类测试
{
公众:
Test(){coutmake\u shared()
应该足够了,您没有打印副本构造函数make\u shared(Test())
make\u shared()
应该足够了,您没有打印副本构造函数make\u shared(Test())
使用用户提供的析构函数,编译器不会生成移动-constructor@PiotrSkotnicki:更新了语言,以提及省略的副本和/或编译器生成副本ctor的可能性,尽管用户定义的dtor不推荐使用,但这仍然是可能的。很难跟踪编译器将和不会生成副本ctor的所有场景生成特殊成员函数!使用用户提供的析构函数,编译器不会生成移动-constructor@PiotrSkotnicki:更新语言,以提及省略的副本和/或编译器生成副本ctor的可能性,尽管用户定义的dtor不推荐使用,但这仍然是可能的。很难跟踪编译器将不会生成特殊的成员函数!
constructor
destructor
show
destructor
class Test
{
public:
Test(){ cout << "constructor" << endl; }
~Test(){ cout << "destructor" << endl; }
Test(const Test& other){cout << "copy" << std::endl;}
void show(){ cout << "show" << endl; }
};
int main()
{
vector<shared_ptr<Test>> vec;
vec.push_back(make_shared<Test>(Test()));
vec[0]->show();
vec.clear();
return 0;
}