似乎对Feed向量的迭代不会调用绘图函数。我在里面添加了一些断点,但没有一个断点被触发。
数据是我程序其他部分提供的字符串向量,它可以正常工作(输出文件很好)。
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()
{
}
所以我的问题是:发生了什么?我该如何解决?
PS。我试着保持简单,所以如果我跳过任何重要的细节让我知道,我会交付。
答案 0 :(得分:1)
#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;
}