A.connected_to[0] = &B;
复制一些东西:表达式&B的临时指针值。
向量模板类总是会自动进行复制构造和销毁,但是原始类型的复制构造等价于原始类型的赋值和销毁,包括指针,是无操作的。
指针是一种非常基本的类型 - 使用指针时几乎不会自动为您完成任何事情。在引擎盖下,它只是一个对应于内存地址的整数值。当您取消引用一个指针时,编译器只是相信您该指针持有(或“指向”)正确类型的对象的地址。
例如,给定的类 Foo 和 Bar 没有继承关系:
Foo *ptr1, *ptr2;
Bar *ptr3;
// All pointers are uninitialized.
// Dereferencing them is undefined behavior. Most likely a crash.
// The compiler will almost certainly issue a warning.
ptr1= new Foo(); // ptr1 now points to a valid Foo.
ptr2 = ptr1; // ptr2 points to the same Foo.
ptr3=(Bar*)ptr1; // This is an obvious programmer error which I am making here for demonstration.
// ptr3 points to the same block of memory as ptr1 & 2.
// Dereferencing it is likely to do strange things.
delete ptr1; // The compiler is allowed to set ptr1 to 0, but you can't rely on it.
// In either case dereferencing ptr1 is once again undefined behavior
// and the value of ptr2 is unchanged.
如果在删除后看到ptr1 被取消引用,编译器发出警告的可能性要比初始化前小得多。如果您在通过ptr1 删除对象后取消引用ptr2,它几乎不会发出警告。如果您没有像其他人警告您的那样小心,您的指针向量可能会导致您无意中以这种方式调用未定义的行为。
我将Foo* 的非常错误 转换为Bar*,以说明编译器对您的绝对信任。编译器允许您这样做,并且当您取消引用 ptr3 时,它会愉快地将这些位视为 Bar。
C++ 标准库提供了一些模板类,这些模板类提供了类似指针的行为和更多的自动安全性。例如std::shared_pointer:
std::shared_ptr 是一个管理对象生命周期的智能指针,
通常分配有new。几个shared_ptr 对象可以管理
同一个对象;对象在最后剩下的时候被销毁
shared_ptr 指向它被破坏或重置。对象是
使用删除表达式或提供的自定义删除器销毁
施工期间发给shared_ptr。
如果您的环境还没有提供 c++11 标准库,它可能会提供 boost 库或 std::tr1:: 命名空间。两者都提供了一个非常相似的shared_ptr。 std::auto_ptr,你肯定有,它是类似的,但只允许一个 auto_ptr 在给定时间引用一个对象。 (C++11 引入了std::unique_ptr 作为auto_ptr 的预期替代品。auto_ptr 与大多数标准模板容器不兼容。unique_ptr 可以放在带有std::move 的模板容器中。)
可以通过保留或获取指针并使用它来破坏这些类中的任何一个,例如
Foo *basic_ptr=new Foo();
std::auto_ptr<Foo> fancy_ptr(basic_ptr);
delete basic_ptr; // Oops! This statement broke our auto_ptr.
如果你在自动存储中传入一个变量的地址,你也会破坏它们:
Foo aFoo;
std::auto_ptr<Foo> fancy_ptr(&aFoo); // automatic storage automatically breaks auto_ptr
如果你只使用std::shared_ptr<sn> fresh_sn(new sn()),然后使用std::vector< std::shared_ptr<sn> >,你会没事的。