gpt4 book ai didi

c++ - vector 上的迭代不调用函数

转载 作者:行者123 更新时间:2023-11-28 05:01:10 25 4
gpt4 key购买 nike

似乎对 feed vector 的迭代不会调用绘制函数。我在里面加了几个断点,都没有触发。

数据是我程序的其他部分提供的字符串 vector ,它工作正常(输出文件没问题)。

std::vector<std::unique_ptr<NewsRenderer>> feed;

std::unique_ptr<NewsRenderer> ptr=std::make_unique<NewsRenderer>(NewsRenderer(sf::Vector2i(300, 100), "test-title", "test-url"));
feed.push_back(std::move(ptr));

myfile.close();

while (window.isOpen())
{
window.clear(sf::Color::White);
for (int i = 0; i < feed.size(); i++)
{
feed[i]->draw(0, 100 * i);
}

window.display();
}

有NewsRenderer.h

#include "News.h"

#include <iostream>
class NewsRenderer
{
public:
NewsRenderer(std::string title, std::string url, std::string decription="");
void draw(int x, int y);
~NewsRenderer();
private:
News* newsData;
};

和 NewsRenderer.cpp

NewsRenderer::NewsRenderer(std::string title, std::string url, std::string decription)
{
newsData = new News{ title, url, decription };
}

void NewsRenderer::draw(int x, int y)
{
draw(title, x, y); //magic, but I didn't want to use any libraries in this example
}

NewsRenderer::~NewsRenderer()
{
}

所以我的问题是:发生了什么事?我该如何解决?

附言。我尽量保持简单,所以如果我跳过任何重要的细节,请告诉我,我会提供。

最佳答案

#include <vector>
#include <string>
#include <memory>
#include <iostream>

struct News {
const std::string title;
const std::string url;
const std::string description;
};

struct NewsRenderer {
NewsRenderer(std::string title, std::string url, std::string description="")
: data(new News{title, url, description})
{ }

~NewsRenderer()
{ delete data; }

void draw() const
{ std::cout << data->title << " - " << data->url << " - " << data->description << '\n'; }

const News* data;
};

void foo() {
std::cout << "foo()\n";
std::vector<std::unique_ptr<NewsRenderer>> feed{};

auto p = std::make_unique<NewsRenderer>("title", "url", "description");
// ^^^^^^^^^^^^ <= forwards arguments to NewsRenderers constructor
feed.push_back( std::move(p) );
for(auto& nr : feed) nr->draw();
}

void bar() {
std::cout << "bar()\n";
std::vector<std::unique_ptr<NewsRenderer>> feed{};

auto p = std::make_unique<NewsRenderer>(NewsRenderer{"title", "url", "description"});
// ^^^^^^^^^^^^ <= tries to invoke copy constructor, not safe
feed.push_back( std::move(p) );
for(auto& nr : feed) nr->draw();
}

int main() {
foo();
bar();
return 0;
}

关于c++ - vector 上的迭代不调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com