小编Rob*_*Rob的帖子

将相似类型的成员变量组合在一起

在编写类时,您是否将相同类型的成员变量组合在一起?这样做有什么好处吗?例如:

class Foo
{
private:
    bool a_;
    bool b_;
    int c_;
    int d_;
    std::string e_;
    std::string f_;
    ...
};
Run Code Online (Sandbox Code Playgroud)

相反:

class Bar
{
private:
    std::string e_;    
    bool a_;
    int d_;
    bool b_;
    std::string f_;
    int c_;    
    .
Run Code Online (Sandbox Code Playgroud)

..};

或者你只是按照它们被添加的顺序拥有它们?

c++

1
推荐指数
2
解决办法
1153
查看次数

滚动我自己的例外

我正在编写一些新代码,它将抛出一个自定义异常 - 我想包含一个错误字符串和一个状态代码.哪个类应该是异常派生的? std::exceptionstd::runtime_error?还有其他'陷阱'需要担心吗?我在考虑以下内容:

class MyException : public std::exception(?)
{
public:
    enum Status
    {
        ERROR_FOO,
        ERROR_BAR,
        ...
    };

    MyException(const std::string& error, Status code) :
        error_(error), code_(code)
    {
        ...
    }

    virtual const char* what() const
    {
        return error_.c_str();
    }

    Status code() const
    {
        return code_;
    }
private:
    std::string error_;
    Status code_;
};
Run Code Online (Sandbox Code Playgroud)

然后在代码中:

throw MyException("Ooops!", MyException::ERROR_BAR);
Run Code Online (Sandbox Code Playgroud)

c++ exception

1
推荐指数
2
解决办法
887
查看次数

qsort线程安全吗?

我有一些旧的代码,用于qsort对MFC CArray的结构进行排序,但我看到偶尔的崩溃可能会导致多个线程同时调用qsort.我使用的代码看起来像这样:

struct Foo
{
  CString str;
  time_t t;

  Foo(LPCTSTR lpsz, time_t ti) : str(lpsz), t(ti)
  {
  }
};

class Sorter()
{
public:
    static void DoSort();
    static int __cdecl SortProc(const void* elem1, const void* elem2);
};

...

void Sorter::DoSort()
{
  CArray<Foo*, Foo*> data;
  for (int i = 0; i < 100; i++)
  {
    Foo* foo = new Foo("some string", 12345678);
    data.Add(foo);
  }

  qsort(data.GetData(), data.GetCount(), sizeof(Foo*), SortProc);
  ...
}

int __cdecl SortProc(const void* elem1, …
Run Code Online (Sandbox Code Playgroud)

c++ mfc qsort

1
推荐指数
1
解决办法
2250
查看次数

std :: map :: const_iterator模板编译错误

我有一个模板类,其中包含一个std::map存储指向T的指针,它拒绝编译:

template <class T>
class Foo
{
public:
  // The following line won't compile
  std::map<int, T*>::const_iterator begin() const { return items.begin(); }

private:
  std::map<int, T*> items;
};
Run Code Online (Sandbox Code Playgroud)

gcc给我以下错误:

error: type 'std::map<int, T*, std::less<int>, std::allocator<std::pair<const int, T*> > >' is not derived from type 'Foo<T>'
Run Code Online (Sandbox Code Playgroud)

同样,以下内容也拒绝编译:

typedef std::map<int, T*>::const_iterator ItemIterator;

但是,使用不包含模板类型的映射可以正常工作,例如:

template <class T>
class Foo
{
public:
  // This is OK
  std::map<int, std::string>::const_iterator begin() const { return items.begin(); }

private:
  std::map<int, std::string> items;
};
Run Code Online (Sandbox Code Playgroud)

我认为这与模板有关并且引发了一个问题 - 如何将一个返回const_iterator …

c++ templates

1
推荐指数
1
解决办法
2584
查看次数

标签 统计

c++ ×4

exception ×1

mfc ×1

qsort ×1

templates ×1