【发布时间】:2019-05-09 13:59:19
【问题描述】:
我为 SDL2 库方法创建了包装函子,以使用自定义删除器返回智能指针。 unqiue_ptr(图像类)似乎工作正常,但在构建期间返回 shared_ptr(窗口类)的类会出现以下错误:
'<function-style-cast>': cannot convert from 'initializer list' to 'std::shared_ptr<SDL_Window>'
这里的SDL_CreateWindow 返回原始SDL_Window*,IMG_Load 返回原始SDL_Surface*。
我尝试将Deleter 移至公共并删除 Window 类的复制限制,但仍然失败并出现同样的错误。此外,如果我只是从 Window 的函数转换中返回 nullptr,那么它构建得很好。所以问题似乎与 shared_ptr 本身的创建有关。让我感到困惑的是,为什么它可以与 unique_ptr 一起正常工作,但不能与 shared_ptr 一起工作。
#pragma once
#include <memory>
#include <SDL.h>
#include "Uncopyable.h"
// fails during build with error: '<function-style-cast>':
// cannot convert from 'initializer list' to 'std::shared_ptr<SDL_Window>'
class Window:private Uncopyable {
private:
public:
class Deleter {
void operator()(SDL_Window *window) {
SDL_DestroyWindow(window);
}
};
static const int SCREEN_WIDTH = 800;
static const int SCREEN_HEIGHT = 600;
std::shared_ptr<SDL_Window> operator()() const {
return std::shared_ptr<SDL_Window>(
SDL_CreateWindow("SDL Tutorial",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN),
Deleter());
}
};
#pragma once
#include <memory>
#include <string>
#include <SDL.h>
#include <SDL_image.h>
#include "Uncopyable.h"
// builds fine
class Image: private Uncopyable {
public:
class Deleter{
void operator()(SDL_Surface *image) {
SDL_FreeSurface(image);
}
};
std::unique_ptr<SDL_Surface, Deleter> operator()(const std::string &path) const {
return std::unique_ptr<SDL_Surface, Deleter>(
IMG_Load(path.c_str()),
Deleter());
}
};
预期结果:Window 类应该像 Image 类一样构建而没有错误
实际结果:Window 类失败并出现上述错误,而 Image 类构建良好
更新:通过将 shared_ptr 创建逻辑移动到简单函数进一步缩小范围,我发现删除自定义 Deleter() 会删除构建错误。所以它似乎是罪魁祸首。但是我需要删除器,而且为什么使用 unique_ptr 的 Image 可以正常工作。
【问题讨论】:
标签: c++ shared-ptr