我正在处理导致我遇到与下面示例相似的情况的事情。我希望 b 在 test()之后指向 a 。是否有可能或创建副本是唯一的解决方案?
感谢。
void test(Object* a, Object* b)
{
std::cout << "test a: " << a << std::endl;
std::cout << "test b: " << b << std::endl;
b = a;
std::cout << "test b assigned: " << b << std::endl;
}
int main()
{
Object* a = new Object();
Object* b = nullptr;
test(a, b);
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
delete a;
delete b;
}
test a: 0x1aa8930
test b: 0
test b assigned: 0x1aa8930
a: 0x1aa8930
b: 0
答案 0 :(得分:4)
要修改指针,您需要:
void test(Object **a, Object **b)
test(&a,&b);
void test(Object *&a, Object *&b)
test(a,b);
对于a
,您不必传递指针指针或指针引用(除非您计划将来修改它),但对于b
您必须要修改它。
P.S。将您的void main()
更改为int main()
答案 1 :(得分:1)
你可以这样做:
void test(Object* a, Object*& b)
{
std::cout << "test a: " << a << std::endl;
std::cout << "test b: " << b << std::endl;
b = a;
std::cout << "test b assigned: " << b << std::endl;
}
int main()
{
Object* a = new Object();
Object* b = NULL;
test(a, b);
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
delete a, b;
}
输出将是:
test a: 0x7a0d28
test b: 0
test b assigned: 0x7a0d28
a: 0x7a0d28
b: 0x7a0d28
因为有问题,你已经传递了b的值,而不是对它的引用,这是修改它所必需的。变量只能通过函数修改,如果该函数接收到这些变量的地址,并且只能通过指针(对象**)或引用(对象*&amp;)
来完成。答案 2 :(得分:0)
现在我们有一种名为shared_ptr
的东西,它可以满足您的需求。另外,在你完成它之后,你不必清理它!
示例:
#include <memory>
#include <iostream>
using Object = int;
void test(const std::shared_ptr<Object>& a, std::shared_ptr<Object>& b)
{
b = a;
std::cout << "test b assigned: " << b.get() << "\n";
}
int main()
{
auto a = std::make_shared<Object>();
std::shared_ptr<Object> b;
std::cout << "test a: " << a.get() << "\n";
std::cout << "test b: " << b.get() << "\n";
test(a, b);
std::cout << "test a: " << a.get() << "\n";
std::cout << "test b: " << b.get() << "\n";
return 0;
}
输出(g ++ 5.4.0):
test a: 0x21e2c30
test b: 0
test b assigned: 0x21e2c30
test a: 0x21e2c30
test b: 0x21e2c30