使用functioncall初始化字符串成员c ++

Joh*_*nes 0 c++ initialization member

对象有一个字符串,需要构造.

#include <string>

class SDLException
{
private:
    std::string what_str;
public:
    SDLException(const std::string &msg);
    ~SDLException(void);
};
Run Code Online (Sandbox Code Playgroud)

该字符串具有隐藏的依赖关系,我需要考虑(SDL_GetError()).我可以在函数中构造字符串.但我不知道如何使用该函数的返回值来初始化字符串成员.

#include "SDLException.hpp"

#include <sstream>
#include <string>
#include <SDL.h>

static void buildSTR(const std::string &msg)
{
    std::ostringstream stream;
    stream << msg << " error: " << SDL_GetError();
    std::string str =  stream.str();
    //if i return a string here it would be out of scope when i use it
}

SDLException::SDLException(const std::string &msg)
    : what_str(/*i want to initialise this string here*/)
{}

SDLException::~SDLException(void){}
Run Code Online (Sandbox Code Playgroud)

如何what_str以最小的开销初始化成员?内容what_str应该等于的内容str.

Jul*_*ian 5

你的buildSTR()函数应该返回一个字符串:

static std::string buildSTR(const std::string &msg)
{
    std::ostringstream stream;
    stream << msg << " error: " << SDL_GetError();
    return stream.str();
}
Run Code Online (Sandbox Code Playgroud)

这里使用它没有问题:

SDLException::SDLException(const std::string &msg)
    : what_str(buildSTR(msg))
{ }
Run Code Online (Sandbox Code Playgroud)

或者,您可以省略sstreaminclude并简单地使用字符串连接,因为std::string有一个运算符重载以允许连接const char*.例如:

SDLException::SDLException(const std::string &msg)
    : what_str(msg + " error: " + SDL_GetError())
{ }
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记阅读高度相关的RVO和NRVO,也不要忘记将字符串意外复制的性能与抛出异常的性能进行比较(提示:在许多平台上投掷会更多)昂贵). (2认同)