用右值初始化智能指针
Initialize smart pointer with rvalue
我想了解我在创建 new_class2
时遇到的问题是否是因为 std::make_shared
returns 和 rvalue
。如果是这样,除了我已经在 new_class
.
中创建的对象之外,还有哪些初始化对象的其他方法?
#include <iostream>
#include <memory>
#include <vector>
class Foo
{
private:
std::shared_ptr<std::vector<int>> common_number;
public:
Foo(std::shared_ptr<std::vector<int>> &integer_vec) : common_number(integer_vec)
{
for (auto &v : *integer_vec)
{
std::cout << v << std::endl;
}
}
~Foo()
{
}
void addTerm(int integer)
{
common_number->push_back(integer);
}
void print()
{
for (auto &v : *common_number)
{
std::cout << v << std::endl;
}
}
};
int main()
{
std::vector<int> vec = {};
std::shared_ptr<std::vector<int>> int_ptr = std::make_shared<std::vector<int>>(vec);
Foo new_class(int_ptr);
Foo new_class1(int_ptr);
new_class1.addTerm(5);
new_class.print();
new_class.addTerm(1);
new_class1.print();
Foo new_class2(std::make_shared<std::vector<int>>(vec));
return 0;
}
我确实遇到了编译错误:
error: invalid initialization of non-const reference of type ‘std::shared_ptr<int>&’ from an rvalue of type ‘std::shared_ptr<int>’ Foo new_class2(std::make_shared<int>(1));’
正如@Elijay 和@underscore_d 在评论中提出的那样,按值传递然后使用 move()
将是推荐的方法
Foo(std::shared_ptr<std::vector<int>> integer_vec) : common_number(std::move(integer_vec))
{
for (auto &v : *integer_vec)
{
std::cout << v << std::endl;
}
}
我想了解我在创建 new_class2
时遇到的问题是否是因为 std::make_shared
returns 和 rvalue
。如果是这样,除了我已经在 new_class
.
#include <iostream>
#include <memory>
#include <vector>
class Foo
{
private:
std::shared_ptr<std::vector<int>> common_number;
public:
Foo(std::shared_ptr<std::vector<int>> &integer_vec) : common_number(integer_vec)
{
for (auto &v : *integer_vec)
{
std::cout << v << std::endl;
}
}
~Foo()
{
}
void addTerm(int integer)
{
common_number->push_back(integer);
}
void print()
{
for (auto &v : *common_number)
{
std::cout << v << std::endl;
}
}
};
int main()
{
std::vector<int> vec = {};
std::shared_ptr<std::vector<int>> int_ptr = std::make_shared<std::vector<int>>(vec);
Foo new_class(int_ptr);
Foo new_class1(int_ptr);
new_class1.addTerm(5);
new_class.print();
new_class.addTerm(1);
new_class1.print();
Foo new_class2(std::make_shared<std::vector<int>>(vec));
return 0;
}
我确实遇到了编译错误:
error: invalid initialization of non-const reference of type ‘std::shared_ptr<int>&’ from an rvalue of type ‘std::shared_ptr<int>’ Foo new_class2(std::make_shared<int>(1));’
正如@Elijay 和@underscore_d 在评论中提出的那样,按值传递然后使用 move()
将是推荐的方法
Foo(std::shared_ptr<std::vector<int>> integer_vec) : common_number(std::move(integer_vec))
{
for (auto &v : *integer_vec)
{
std::cout << v << std::endl;
}
}