好吧,所以我最后一次以C++为生,std::auto_ptr所有的std lib都可用,而且boost::shared_ptr风靡一时.我从未真正研究过提供的其他智能指针类型.我知道C++ 11现在提供了一些类型的提升,但不是全部.
那么有人有一个简单的算法来确定何时使用哪个智能指针?优选地包括关于哑指针(诸如原始指针T*)和其他增强智能指针的建议.(像这样的东西会很棒).
参考代码:
#include <vector>
#include <iostream>
class Func {
public:
virtual void call() {
std::cout<< "Func -> call()" << std::endl;
}
};
class Foo : public Func {
public:
void call() {
std::cout<< "Foo -> call()" << std::endl;
}
};
class Bar : public Func {
public:
void call() {
std::cout<< "Bar -> call()" << std::endl;
}
};
int main(int argc, char** argv) {
std::vector<Func> functors;
functors.push_back( Func() );
functors.push_back( Foo() );
functors.push_back( Bar() );
std::vector<Func>::iterator iter;
for (iter = functors.begin(); …Run Code Online (Sandbox Code Playgroud) 我似乎无法让多级继承函数调用正常工作.对于我的结构,我有一个"实体"作为主要的超级类
实体 - >子弹,代理
特工 - >球员,敌人
敌人 - > BasicEnemy
在每个中我都有一个"更新"功能
class Entity
{
public:
Entity();
virtual ~Entity();
//stuff
virtual Bullet update(float deltaTime);
}
class Agent : public Entity
{
public:
Agent();
virtual ~Agent();
virtual Bullet update(float deltaTime);
class Player : public Agent
{
public:
Player();
~Player();
Bullet update(float deltaTime) override;
class Enemy : public Agent
{
public:
Enemy();
virtual ~Enemy();
virtual Bullet update(float deltaTime);
class BasicEnemy : public Enemy
{
public:
BasicEnemy();
~BasicEnemy();
Bullet update(float deltaTime) override;
Run Code Online (Sandbox Code Playgroud)
我创建玩家,敌人和子弹对象然后将它们传递给实体向量,但每当我打电话时 …
我正在阅读 C++ 中的智能指针,我很惊讶超过 99% 的给定示例实际上是相当糟糕的示例,因为在这些情况下可以避免动态分配。我同意仅在 STL 容器不起作用的上下文中使用智能指针。例如,在动态数组 ( std::vector) 中,性能很重要,因此最好拥有经过良好测试的代码而不使用任何智能指针。
这里我认为是一个不好的例子,因为在这种情况下unique_ptr不是解决方案,但堆栈分配将是正确的方法。
MyObject* ptr = new MyObject();
ptr->DoSomething();
delete ptr;
Run Code Online (Sandbox Code Playgroud)
那么什么是 C++ 中智能指针的好例子或用途呢?
换种说法是什么设计模式需要将指针的所有权转移到另一个对象?